The task is to create a program that can do the maximum factorial possible by the machine using "for" cycle.
I understood i have to use bigger data types (the biggest one is "long long", correct me if i'm wrong), and i also understood the concept of the factorial.
Otherwise, i really do not know how to apply what i know in c++.
these is the idea at the base of what i wrote down as of now:
#include <cstdlib>
#include <iostream>
#include <math.h>
include namespace std;
int main(int argc, char *argv[])
{
long long i, factorial;
cin<<factorial;
{
for(long long i=1; i=factorial; i++)
{
factorial=factorial*i
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
Problems are:
I don't know if the code it's wrote correctly
by doing "factorial=factorial*i", the "i=factorial" in the "for" cycle doesn't make sense, since it will stop the program before it has to.
This being said, I would like to point out that i am in high school, my programming knowledge is really poor, and for this reason every kind of advice and information is very well accepted :).
Thanks in advance
Maybe you want to compute the maximum factorial that will fit in an unsigned long long data type.
But let us look at the horrible program. I add comments with the problems.
#include <cstdlib> // Not to be used in C++
#include <iostream>
#include <math.h> // Not needed
include namespace std; // Completely wrong statement. But even if you would have done it syntactically correct, it should never be used
int main(int argc, char *argv[]) // Neither args nor argv is used
{
long long i, factorial; // i will be redefine later. factorial is not initialized
cin<<factorial; // You want to stream somethin into std::cin?
{
for(long long i=1; i=factorial; i++) // Thats heavy stuff. i=factorial? Nobody know, what will happen
{
factorial=factorial*i // Semicolon missing
}
}
system("PAUSE"); // Do not use in C++
return EXIT_SUCCESS; // EXIT_SUCCESS is not defined
}
Maybe the below could give you an idea
#include <iostream>
int main() {
unsigned long long number{};
unsigned long long factorial{1};
std::cin >> number;
for (unsigned long long i{ 1 }; i <= number; ++i)
factorial = factorial * i;
std::cout << factorial;
}
Related
my code is shown here:
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
using std::string;
using std::endl;
using std::cout;
using std::cin;
struct funcs
{
std::vector<int> values;
int sum;
void createVectorValues(){
while(values.size() < 100)
{
int x = rand() % 100;
values.push_back(x);
}
for(int& a : values)
{
sum += 1;
}
cout << sum;
}
};
int main()
{
srand;
funcs myFunct;
myFunct.createVectorValues();
}
the following code results in a large value such as -858993360
How can I change this code so that it can function properly
You didn't define a constructor for funcs, so you get the default constructor, which invokes the default constructor of each member. This means the int member sum is left with an indeterminate value. See Does the default constructor initialize built-in types?. You probably want to write a constructor that initializes sum to 0.
srand; isn't a function call. It's valid syntax, because srand evaluates to a pointer to the srand function, but it's an expression with no side effects, so it does nothing. Much as if you had written 3;. To call the function, you need srand(arg), where arg is an appropriate integer. Or, switch to the C++11 random number generation features, which are much more powerful and usually have better randomness.
Try this:
int main(int, char **) {
funcs myFunct;
myFunct.createVectorValues();
}
Although no idea why your antivirus is involved. That might be a separate issue.
In a program I am currently working on I have a template function included in a separate .h file that reads in five columns of data from a .txt file. The data is passed to the main program and in this instance I only care about the array title "MISC_DATA". I am trying to determine the largest value in the array "MISC_DATA" and have written another function that the data has to be passed to, in order to determine this. However, the compiler is telling me that it does not recognize the function call "Maximum_Value". I am pretty sure that it is having problems with the variable MISC_DATA included in the routine call and not the function itself. Either it does not recognize MISC_DATA as an array or I have the syntax wrong. I'm only including the important snippets of code to make it more readable. The Read_Five_Columns functions works fine, it is the function "Maximum_Value", which is not being recognized by the compiler because of how the pointer array MISC_DATA is written in the main program. For clarification the variable MISC_DATA in the function call is a float which contains the array and the variable "size_Mis" is an integer which contains the array size. Any thoughts would be appreciated.
int main(int argc, const char * argv[]) {
#include "Use_RNG.h"
#include "Read_Columnar_File.h"
#include <fstream>
#include <iostream>
std::vector<std::string> str3;
std::vector<int> str4;
std::vector<char> str5;
std::vector<int> str6;
unsigned long size_Mis;
std::vector<float> MISC_DATA; // Reads in Misc. spending data
char File1[8];
strcpy(File1, "Misc.txt");
Read_Five_Columns(File1,MISC_DATA,str3,str4,str5,str6);
str3.clear(); str4.clear(); str5.clear(); str6.clear();
size_Mis = MISC_DATA.size();
float value;
value = Maximum_Value(MISC_DATA,size_Mis);
end_time = clock();
std::cout << std::endl << "Total Time: " << (end_time-start_time)/CLOCKS_PER_SEC << std::endl;
return 0;
}
int Maximum_Value(float *array,int array_size)
{
float max = 0;
for(int i =10; i < array_size-1; i++)
{
if(array[i] > max) max = array[i];
}
return max;
}
There are four problems I see here.
int main(int argc, const char * argv[]) {
#include "Use_RNG.h"
#include "Read_Columnar_File.h"
#include <fstream>
#include <iostream>
All of this stuff is in the wrong order. You should not include system header files into function bodies, and typically you include standard library stuff before other stuff. Fix it to read like this:
#include <fstream>
#include <iostream>
#include "Use_RNG.h"
#include "Read_Columnar_File.h"
int main(int argc, const char * argv[]) {
Secondly, you don't declare Maximum_Value before you use it. You need to either move the definition of this function before the definition of main() or you need to add a prototype before main():
int Maximum_Value(float *array,int array_size);
int main(int argc, const char * argv[]) {
Then, you attempt to pass an std::vector<float> as a float* which does not work:
value = Maximum_Value(MISC_DATA,size_Mis);
However, because the storage for vectors is guaranteed to be contiguous and laid out like an array, you can pass a pointer to the first member safely:
value = Maximum_Value(&MISC_DATA[0],size_Mis);
Finally, you return int from Maximum_Value when you should probably be returning float.
If possible I would suggest leveraging std::max_element, which is part of the standard <algorithm> header:
// If you don't have C++11 then use std::vector<float>::iterator instead of auto.
auto max = std::max_element(MISC_DATA.begin(), MISC_DATA.end());
Now max is an iterator to the largest element, so *max would be the largest float itself.
(If the input range was empty, then max will be equal to MISC_DATA.end(), so the equivalent to your function would be value = max == MISC_DATA.end() ? 0f : *max;.)
While working on a fairly large project, I happened to notice that one of my functions that is supposed to return a Long value is either returning an Integer. I reproduced the error in a very small environment thinking that it would make the problem clear to me, but I'm still not seeing the issue. The input is 1.123, and the return value is 1. If I input any Long, for example; 123.456, it will only return 123. What am I not seeing?
Source1.cpp
#ifndef HEADER_H
#define HEADER_H
using namespace std;
class testClass
{
private:
long m_testLong = 0.0;
public:
long getTestLong();
void setTestLong(long sn);
};
#endif
Header.h
#include "Source1.cpp"
#include <string.h>
void testClass::setTestLong(long sn)
{
m_testLong = sn;
}
long testClass::getTestLong()
{
return m_testLong;
}
Source.cpp
#include <iostream>
#include "Source1.cpp"
#include "Header.h"
using namespace std;
int main(void)
{
testClass *myClass = new testClass;
cout << "Setting test long value using setTestLong function -- 1.123" << endl;
myClass->setTestLong(1.123);
long tempTestLong = 0.0;
tempTestLong = myClass->getTestLong();
cout << tempTestLong << endl;
system("Pause");
return 0;
}
OK, so the answer was painfully simple. I hadn't worked with longs before, but I thought I knew what they were. I didn't.
So longs and integers both are whole numbers, and having the type listed as long made me assume an integer wouldn't work, and I tested the function with a double because of my misunderstanding. Thanks for the help!
The long and int types are integral types, they can only hold whole numbers like 7 or 42.
You should be using float or double as a type, preferably the latter for increased range and precision. That will allow you to hold real numbers such as 3.141592653589 or 2.718281828459.
Long is an integer. Assigning a floating point value to integer causes rounding.
You want double or float.
I am brand new to programming and I have just finished reading the Book C for Dummies by Dan Gookin. But I thought I am trying to make tiny programs to get a feel of the language.
I learned that there is a random counter in C (which is not that random), and apparently using the computers internal clock helps making the random counter more random. I saw a code example in the book and it work when I want to printf() random numbers in a grid. But now I would like the program to limit it to only 3 numbers but instead of printing out the numbers in digits I'm interested in learning how to have the computer return printf() functions in a random manner. It doesn't have to be printf() it really can be any function, but this seems to be the easiest way to check.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int rnd(int range);
void seedrnd(void);
int main()
{
int x;
seedrnd();
for(x=0;x<1;x++)
// printf("%i\t" ,rnd(3));
if(seedrnd==0)
printf("Zero");
else if(seedrnd==1)
printf("One");
else
printf("Two");
return(0);
}
int rnd(int range)
{
int r;
r=rand()%range;
return(r);
}
void seedrnd(void)
{
srand((unsigned)time(NULL));
}
You put seedrnd (a pointer to seedrnd function) instead of a call to rnd(int). You meant to call a function, not to use its name, in comparison expressions:
for(x=0;x<1;x++) {
int r = rnd(3); // Call rnd(3)
printf("%i\t", r);
if(r==0) // Use r, not seedrnd
printf("Zero");
else if(r==1)
printf("One");
else
printf("Two");
}
trying to get ‘sval’ to contain the string “$1” – “$500” for array indexes 0-499. in the following code, however itoa is giving me strange strings in the code below:
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct data_t {
int ival;
char *sval;
} data_t;
void f1(data_t **d);
int main()
{
data_t *d;
d=static_cast<data_t*>(malloc(500)); //is this even needed?
d = new data_t[500];
f1(&d);
}
/* code for function f1 to fill in array begins */
void f1(data_t **d)
{
int i;
char str[5];
for (int i=0; i<500; i++)
{
(*d)[i].ival=i+1;
itoa (i,str,10);
(*d)[i].sval= str;
}
}
it also seems itoa has been depreciated, but that was what i got when i googled int to string
You don't need ltoa, cout should be just fine. Why do you need to keep the number and its string representation in the array? when you do cout << 10 you get "10" on the output, you don't need any conversions of your own
You, on the other hand, do ltoa without allocating any memory for the strings, which is not healthy as you have probably noticed. You use a local variable (the same, for all the 500 array members), which you try to access after you exit the function - a big no-no, its undefined behavior.
And:
d=static_cast<data_t*>(malloc(500)); //is this even needed?
d = new data_t[500];
No. Not only not needed - shouldn't be there at all! When in C++ - use new and delete, never malloc, that's a C function.