0

I have added a first version of my code, however it is unable to compile and I just cannot figure out why.

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

int main(void)
 {
int i = 0;
float change;

//Prompt user for input 
     do
     {
         float change = get_float("Change owed");
     }
     while (change < 0);
  
  //convert change into cents
    int cents = round(change * 100);

while (cents >= 25)
    {
        cents -= 25;
        i++;
    }

while (cents >= 10)
    {
        cents -= 10;
        i++;
    }

while (cents >= 5)
    {
        cents -= 5;
        i++;
    }

while (cents >= 1)
    {
        cents -= 1;
        i++;
    }
printf("%i\n", i);

 }



OUTPUT
$ make cash
clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    cash.c  -lcrypt -lcs50 -lm -o cash
cash.c:13:16: error: declaration shadows a local variable [-Werror,-Wshadow]
         float change = get_float("Change owed");
               ^
cash.c:8:7: note: previous declaration is here
float change;
      ^
cash.c:15:13: error: variable 'change' is uninitialized when used here
      [-Werror,-Wuninitialized]
     while (change < 0);
            ^~~~~~
cash.c:8:13: note: initialize the variable 'change' to silence this warning
float change;
            ^
             = 0.0
2 errors generated.
<builtin>: recipe for target 'cash' failed
make: *** [cash] Error 1
1

This is a scope problem, the variable "change" declared in main is visible in the whole main program, but when declaring change in the DO-WHILE loop, this second variable is different from the first change that is shaded by this second. The reason is the rules of scope of a variable, you must have these clear rules, in general the variables declared within a function or block of code (a loop for example), are only known within the scope of that function or block, the solution is not to declare the variable again, it is also convenient to initialize the variables:

float change = 0.0;

//Prompt user for input 
     do
     {
         change = get_float("Change owed");
     }
     while (change < 0);
| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .