0

It's problem that I'm trying to solve for my beginner programming class. I need to enter change and calculate how many coins I need to give back.

this is my code:

int main(void)
{    
    //prompts user for amount of change and check the value of the imput
    int n = get_float("enter change owned: ");
    
    //converts to p.
    int change = n * 100; 
    
    if (change > 0)
    {
        printf("total change is: %ip\n" , change ); 
    } 
    else
    {
        printf(" ERROR: change given needs to be positive value!\n");
    }
    while(n < 0); 
    int i = 0;
    
    //calculate quarters
    while (change >= 250) 
    {
        n = change - 250;
        i++;     
    }
    
    //calculate dimes
    while (change >= 100) 
    {
        n = change - 100;
        i++;     
    }
    //calculate nickels
    while (change >= 50) 
    {
        n = change - 50;
        i++;     
    }
    //calculate pennies
    while (change >= 1) 
    {
        n = change - 1;
        i++;     
    }
    printf("%d\n", i);    
}

I don't understand why when I enter n = 2.50 and program needs to calculate change as n = n * 100 it outputs result as 200 :S. also my program compiles but then when I run it I get following msg: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'

1
  • You do not update the change variable, so your loop are infinite. Commented Aug 16, 2019 at 10:48

1 Answer 1

2
int n = get_float("enter change owned: ");

it casts float as integer, so 2.4 becomes 2. Change to :

float n = get_float("enter change owned: ");

also you might want to check this line :

printf("total change is: %ip\n" , change ); 

to print out integer i would recommend :

printf("total change is: %d\n" , change ); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.