Search code examples
ccs50boolean-expression

Wrong results with variables operations in C


I am trying to write this code:

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

int main(void)
{
    float input;
    int quarters, cdimes, ldimes, nickels, pennies, left = 0, overleft, overleft2 = 0;
   
    do
    {
        input = get_float("Enter a positive value between 0 and 1: ");
    }
    while (input <= 0);
    int cents = round(input * 100);
    
    if (cents >= 25)
    {
        quarters = cents/25;
        **left = cents-(quarters*25);**
        printf ("Number of quarters is %i and the money left is %i", quarters, left);
    }
   else if (cents >= 10)
   {
        cdimes = cents/10; 
        **overleft2 = cents-cdimes*10;**
        printf ("Number of cdimes is %i and overleft2 is %i", cdimes, overleft2);
   }

         if (left >= 10)
        {   
        ldimes = left/10;
        overleft = left - ldimes*10;
        printf ("Number of ldimes is %i. Over left is %i", ldimes, overleft);
        }

But in the highlighted parts, the program is giving me wrong values. For example, when I input the number 0.6, the program multipley by 100 and round it (so now I have the number 60). Because 60 is greater than 25, it goes to the first if clause. However, when I want to subtract the number of quarters of the user's input, it does not give the correct value. What can I do?


Solution

  • Drop left, just use cents.

    // left = cents-(quarters*25);
    cents %= 25;
    

    Remove else to check for quarters and dimes.

    // else if (cents >= 10)
    if (cents >= 10)
    

    Likely other issues too.