error: ISO C forbids comparison between pointer and integer - c++

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");
}

Related

Need help creating a program to factorize numbers

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;
}

Declaring int object in c++

I am new to C++ and I am solving some easy exercises. I was solving one problem when I came across a behavior that I cannot explain.
My function takes 2 arrays as arguments and I must return sum of all elements in these arrays. My code:
#include <vector>
using namespace std;
int arrayPlusArray(vector<int> a, vector<int> b){
int c=0;
for (auto k : a){
c += k;}
for (auto k : b){
c += k;}
return c;
}
This works, but as soon as I write int c; instead of int c=0; it does not work correctly anymore. I thought that when I write int c; it sets c's value to 0. What is the matter?
Writing int c; does not initialise c (unless c is at global scope or has static storage). Initialisation costs CPU clock cycles so C++ allows the programmer to forgo such unnecessary CPU expenditure at the expense of potential program instability.
In fact, the behaviour on reading an uninitialised variable is undefined (unless it's a char, an signed char or an unsigned char) in C++. Never do it.

Xcode linker command failed with exit code 1 c++

I've written a simple series of functions. When I try to call the last function I get the "linker command" error. The syntax is correct but my program won't compile. Am I missing something or is this an IDE issue?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <time.h>
using namespace std;
// Function Prototypes
int numGen ();
int questSol ();
int questAns ();
int main() {
// Store values of functions in variables
int ans = questAns();
int sol = questSol();
if (ans == sol){
cout << "Very good! Press Y to continue" << endl;
questAns();
} else {
cout << "Incorrect. Please try again" << endl;
cin >> ans;
if(ans == sol){
questAns();
}
}
return 0;
};
//Generates two random numbers between zero and ten and returns those numbers
int numGen () {
srand(time(0));
int one = rand() % 10;
int two = rand() % 10;
return one;
return two;
};
//Takes in the random numbers, multiplies them, and returns that result
int questSol (int one, int two) {
int solution = one * two;
return solution;
}
//Takes in random numbers, displays them in cout statement as question, receives and returns user answer to
//question
int questAns (int one, int two) {
int answer;
cout << "How much is " << one << " times " << two << "? \n";
cin >> answer;
return answer;
}
You forward declare a function:
int questAns ();
And then later define a function with a signature:
int questAns (int one, int two);
In C++, functions can have the same name but have different parameters (overloaded functions), so you've never actually defined the questAns that you forward declare and then try to call.
Note: You have the same problem with questSol.
It looks like you don't quite understand the scope of local variables.
Inside numGen you define two ints, one and two. Variables defined within a block (curly braces: {}) exist only within that block. They are local to it. The identifier is only valid within the inner-most block it's defined in, and once you exit it that memory is freed. Returning two ints like you're trying is also impossible.
It looks like you're expecting those ints to be available to your other two functions.
The smallest change you could make is to make int one and two global variables. This means you define them outside of any block (usually at the very top of your code). Then remove the parameter lists from your function definitions, because all the functions can see the global variables. That's generally considered bad programming practice because in more complex programs globals wreak havoc on your code, but in this simple program it'd work and give you a chance to practice understanding variable scope.
Another solution, more in line with what you were trying, is to define an ARRAY of two ints, and return that. Then pass that array to the other two functions. That'd be a better way to do it, and give you a chance to learn about arrays.
You have several problems:
numGen - You cannot return two separate values this way
// Function Prototypes
int numGen ();
int questSol ();
int questAns ();
Says that you have 3 functions all of which return an int and are called with no parameters - which is how you call them.
So the linker is looking for functions with a fingerprint of int_questSol_void and int_questAns_void - you then declare two functions that return an int and take as inputs 3 ints - these have fingerprints of int_questAns_int_int and int_questSol_int_int.
As a result the linker is moaning that you are calling to functions that it can't find.

C++ Programming Error: expected unqualified-id before "{" token

I am a newbie at C++, and I am trying to make a "calculator" which: adds two numbers, subtracts two numbers, multiplies two numbers, divides two numbers, takes the sine of a number, takes the cosine of a number, or takes the tangent of a number. Here is the code:
#include <iostream>;
#include <cmath>;
#include <string>
int main ()
{}
int ask(std::string operation);
{
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::cin>>operation;
if (operation="Addition")
{
goto Add
}
float Add(float addend1, float addend2, float answer)
{
Add:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
break
}
}
There will be more functions later, but my problem is on line 7. There is an error that says: expected unqualified-id before "{" token. I know my indentation is horrible, but thanks!
You have a lot of issues in your code.
First, as Ivan points out, you are trying to define a function inside of a function (ask() inside main()). That isn't valid.
Second, you have a goto (why?!) attempting to jump to a label in another function. I doubt your compiler will even allow that, but how would you expect that to work? You are attempting to use variables passed to your function addition that don't exist as you never call the function and the stack has never been setup for it. This is bad, don't do it, just call the function properly.
Third, the #include preprocessor directive is terminated with a newline, not a semicolon. That could cause some (relatively) hard to track down compilation errors.
Fourth, you are mistakenly attempting to assign the const char* "Addition" to operation when what you meant to use was the equality operator ==. That won't work ether though because operation is an r-value and cannot be assigned to like that. If you want to modify it you will need to declare it as a pointer, but once again, that's not what you are going for semantically...
If you want to compare strings and (for whatever reason...) are intent on using pointers to char then you should be using strcmp. That said, you are in C++ land, so just use std:string instead.
Try something like this. I haven't enhanced your code in anyway, just made it something that will compile and run. I have made a few changes.
Aside from getting rid of a few syntax errors, your original Add function took the result as a float argument. Assigning to that from within the function would only modify a copy. You would need to take a pointer or reference if you want the caller to see the modified value, but you don't need that at all as you can simply return the result.
The string comparison is case sensitive, so you would probably want to change it to be case insensitive. I'm assuming no localization here :). I'm not performing error checking on the input either, so be aware that it may fail if the user enters something other than a valid floating point number.
#include <iostream>
#include <string>
using namespace std;
void Ask();
float Add( float, float );
int main( size_t argc, char* argv[] )
{
Ask();
return 0;
}
void Ask()
{
cout << "Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
string operation;
cin >> operation;
if( operation == "Addition" )
{
float first = 0, second = 0;
cout << "enter first operand";
cin >> first;
cout << "enter second operand";
cin >> second;
cout << "The result is: " << Add( first, second );
}
}
float Add( float first, float second )
{
return first + second;
}
С++ doesn't allow nested functions. You have function main() and trying to declare function ask() inside it. And compiler doesn't know what you want.
I commented your code a little bit, maybe that gets you started:
#include <iostream>;
#include <cmath>;
#include <string>;
int main () {
int ask (){ //you cannot nest functions in C++
char operation [20]; //why not use the string class if you include it anyway
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){ //you cannot compare char-strings in C++ like that
goto Addition; //don't use goto (I don't want to say "ever", but goto is only used in extremely rare cases) make a function call instead
}
}
float addition(float addend1, float addend2, float answer) //you probably want to declare the variables inside the function
{
Addition: //don't use labels
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Let's try to break this down..
You shouldn't use ; on the precompiler directives.
#include <iostream>;
#include <cmath>;
#include <string>;
Should be
#include <iostream>
#include <cmath>
#include <string>
.
int main () {
int ask (){
See Ivans answer for this
char operation [20];
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){
You can use std::string instead which is alot easier to deal with. Then you can write
#include <string>
...
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::string myString;
getline(cin, myString);
if (myString == "Addition"){
.
goto Addition;
}
}
float addition(float addend1, float addend2, float answer)
{
Not sure what is going on here.. but let's break Addition to it's own function
void Addition(){
// do addition here
}
.
Addition:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Don't forget that you have to define the variables
int addend1;
int addend2;
int answer;
Hope this helps you along the way.
First int ask() what is that.Why do you start a block here.
Second you have two {s and three }s that's because of the ask().
I think that c++ does not support anonymus functions.
Third why do you use goto,when you have a function,just call the function.
Fourh your addition func should either be void or remove it's last parameter.
Also I think that you don't need string.h file unless you use some rather advanced funcs,the char array should be enough for your program.

To compute Euler’s pentagonal number theorem via dynamic programming

Here is a link to the code and I have posted it below too.
#include<math.h>
void pentagon(int n)
{
int k,p[10],a[10],b[10];
if(n<0)
p[n]=0;
if(n==0)
p[n]=1;
for(k=1;k<n;k++)
{
a[k]=((3*pow(k,2))-k)/2;
b[k]=((3*pow(k,2))+k)/2;
}
for(k=1;k<n;k++)
{
p[n]=pow(-1,k-1)(pentagon(n-a[k])+pentagon(n-b[k]));
}
cout<<p[n];
}
int main()
{
pentagon(4);
return(0);
}
I am getting the following error :
In function 'void pentagon(int)':
Line 11: error: call of overloaded 'pow(int&, int)' is ambiguous
compilation terminated due to -Wfatal-errors
Replace 2 with 2.0 as the second argument to pow (line 11, 12).
See also: http://www.cplusplus.com/reference/clibrary/cmath/pow/
Collecting and correcting all the errors (and warnings) leads to the following code (codepad). I made some comments about what changed.
#include <math.h>
#include <iostream> // Some compilers will complain if missing
using namespace std; // Some compilers will complain if missing
// returns int instead of being void
int pentagon(int n)
{
int k,p[10],a[10],b[10];
// recursion end - we want to jump out here right away
if(n<0) return 0;
if(n==0) return 1;
for(k=1;k<n;k++)
{
a[k]=((3*(int)pow(k,2.0))-k)/2; // pow needs double as second argument
b[k]=((3*(int)pow(k,2.0))+k)/2; // and returns double
}
for(k=1;k<n;k++)
{
// pow casting and double as second argument, multiplication with pentagon
p[n]=(int)pow(-1,k-1.0)*(pentagon(n-a[k])+pentagon(n-b[k]));
}
cout<<p[n]<<endl; // cleaner output
return p[n]; // return the calculated value
}
int main()
{
pentagon(4);
return(0);
}
but I guess the underlying algorithm is still wrong, as the output is:
-1084535312
-1084535311
1074838088
0
3
4
0
Here are some errors or improvements I spotted:
Added iostream & using namespace std:
#include <cmath>
#include <iostream>
using namespace std;
Changed pow(k,2) to k*k:
a[k]=((3*(k*k))-k)/2;
b[k]=((3*(k * k))+k)/2;
Add multiplication symbol to p[n] assignment:
p[n] = pow(-1.0,k-1) * (pentagon(n-a[k]) + pentagon(n-b[k]));
The pentagon method needs to return a value in order to use it in the above statement.
You're missing the summation part of the equation.
See http://en.wikipedia.org/wiki/Pentagonal_number_theorem.
Your pentagon function only calculates one term at a time. There is no code that sums all of the terms.