In c this code below shows an error:
expression must have integral or unscoped enum type
illegal left operand has type 'double'
is it possible to correct it without the need to use fmod?
# include <iostream>
using namespace std;
int main()
{
int x = 5, y = 6, z = 4;
float w = 3.5, c;
c = (y w - 0.5) % x * y; // here is the error
cout << "c = " << c << endl;
return 0;
}
CodePudding user response:
You can use type casting to fix it :
c = ((int) (y w - 0.5)) % x * y;
To clarify your response in the comments, changing c to type int still don't work as the part (y w - 0.5) is not evaluated as int but as double. And modulus operation doesn't take that type as an argument.
Full modified code :
#include <iostream>
using namespace std;
int main()
{
int x = 5, y = 6, z = 4;
float w = 3.5, c; //c could still stayed as float
c = ((int) (y w - 0.5)) % x * y; //swapped out here
cout << "c = " << c << endl;
}
Output : c = 24.
To be clear here, this is only a temporary fix for this case, when you know (y w - 0.5) is going to have a clear integer value. If the value is something like 0.5 or 1.447, std::fmod is desirable.
Here's a post on type conversion rules in an expression regarding interaction between float/double and int/long long : Implicit type conversion rules in C operators
