Lucky500
Lucky500

Reputation: 507

Error: invalid operands to binary expression ('float' and 'float')

I apologize if this question has been asked before. I looked around and was not able to find a solution, I am new to C. I understand that I am not able to get a % from a float. How would I be able to capture the remainder of this math, if I am using 2 floats?

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>

/*
** Always use the largest coin possible
** keep track of coins used
** Print the final amount of coins
*/

int main (void)
{
  float change;
  int counter = 0;
  int division;
  //float rem;
  float quarter = 0.25;
  //float quarter = 0.25, dime = 0.10, nickel = 0.05, penny = 0.01;
  /* Prompt user for an amont of change*/
  do{
    printf("How much do we owe you in change? ");
    change = GetFloat();
  }
  while (change <= 0);
  if (change >= quarter)
  {
    division  = (change / quarter);
    counter += division;
    //change = (int)(change % quarter);
    printf("change: %.2f\n", change);
    printf("counter: %d\n ", counter);
  }

  return (0);
}

Upvotes: 1

Views: 5907

Answers (3)

PowerStat
PowerStat

Reputation: 3819

You could implement the modulo yourself:

https://en.wikipedia.org/wiki/Modulo_operation

int a = (int)(change / quarter);
int mod = (int)(change - (quarter * a));

Also it might be possible to do it this way:

long mod = ((long)(change * 1000) % (long)(quater * 1000));

depending on the precision of your floats modify the 1000 and think about dividing the result by 1000!

But maybe it would be better to rethink what you really want as result?

Upvotes: 2

Nishant
Nishant

Reputation: 2619

Just scale up all your variable by 100 and then use integers instead of float.

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>

/*
** Always use the largest coin possible
** keep track of coins used
** Print the final amount of coins
*/

int main (void)
{
    float change_f;
    int change;
    int counter = 0;
    int division;
    //float rem;
    int quarter = 25;
    //int quarter = 25, dime = 10, nickel = 5, penny = 1;
    /* Prompt user for an amont of change*/
    do{
        printf("How much do we owe you in change? ");
        change_f = GetFloat();
    }
    while (change_f <= 0);
    change = (int)(change_f*100);
    if (change >= quarter)
    {
        division  = (change / quarter);
        counter += division;
        //change = (int)(change % quarter);
        printf("change: %.2f\n", change_f);
        printf("counter: %d\n ", counter);
    }

    return (0);
}

NOTE: Choose scale factor according to the input precision i.e if it is 3 decimal digits then choose 1000 and so on.

Upvotes: 0

Gary Sham
Gary Sham

Reputation: 503

You may want to check fmod.

You can also do something like change = change - (int)(change / quarter) * quarter

Upvotes: 6

Related Questions