jjjjj jjjjj - 1 month ago 13
C Question

Why doesn't my counter work?

I was supposed to get user input, a float, then keep track how many times 0.25, 0.10, 0.05, and 0.01 can be subtracted from it using a counter. Then it's supposed to print the number of counts. But when I tried running the code, it gets user input, but when I try any number this shows up:


greedy.c:18:14: runtime error: signed integer overflow: 2147483647 + 1 cannot be >represented in type 'int'


Please point out any errors, here is my code:

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

int main(void)

{

float b;
float a;
int count = 0;
printf("How much change is owed? ");
a = GetFloat();

do
{
b = a - 0.25;
count++;
}
while(a>0.25);

do
{
b = a - 0.10;
count++;
}
while(a>0.10);

do
{
b= a - 0.05;
count++;
}
while(a>0.05);

do
{
b= a- 0.01;
count++;
}
while(a>0.01);
printf("%d coins\n", count);
}

Answer

Instead of "b = a - 0.25;" try "a = a - 0.25;". And the same for the other subtractions. The variable a stays the same now in your loop.