Reputation: 3
While doing CS50 problem set 1 - Cash, I faced the following problem when I try to write my code. I have declared the variables to integer. Why is it still happening? Thanks a lot for the help.
"invalid operands to binary expression ('float' and 'float')"
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(){
float owe_in_dollars;
float owe_in_cent;
int coin_count = 0;
do
{
owe_in_dollars = get_float("Change: ");
}while(owe_in_dollars<0);
owe_in_cent = (int)(owe_in_dollars*100);
if (owe_in_cent%(int)25 > 0){
coin_count++;
}
printf("%i", coin_count);
}
Upvotes: 0
Views: 199
Reputation: 241721
There are several issues with this code, but I think the particular problem which produces the compiler error is
if (owe_in_cent%(int)25 > 0){
owe_in_cent
is a float
. There is no reason for it to be floating point, since you have assigned it to an integer value. But you declared it float
, so that's what it is. 25
is an int
, so there's no point in casting it to an int
, but with or without the cast, it will be converted to a float
in order to do arithmetic with owe_in_cent
, because all arithmetic operators require that there operands be of the same type. Search for "usual arithmetic conversions" for details, but the bottom line is that these automatic conversions are always integer → floating point, never floating point → integer.
Then the problem shows up, because the %
operator requires its operands to be integers, not floating point. There is a math function which can compute a floating point modulus, but you really want integer arithmetic so your best bet is to make owe_in_cent
an int
rather than a float
.
And actually, you really should get into the habit of using double
for floating point values. float
is very imprecise and, other than in video chips and embedded processors, there's no point in using so inexact a representation. It saves you nothing.
Finally, remember two important facts about floating point:
It cannot precisely represent fractions whose denominators are not powers of two. In other words, 5.25 has an exact representation, because .25 is one-quarter, which is a power of two, but 5.26 cannot be exactly represented and will end up being a number either slightly greater than or slightly less than 5.26. when you mulitiply that number by 100, you will end up with something which is slightly more or slightly less than 526.
Casting a floating point number to an integer just drops the fractional part, no matter how close to 1.0 it is. So, for example, (int)525.9997
is 525, not 526. You should be able to see the problem that could produce.
There is a library function called round
which rounds a floating point number to the closest integer, which is probably what you wanted.
Upvotes: 2