Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

c - How to access a variable inside of an if-statement

This is a section of my function where if the scores were shifted (1) then it prints "Shift amount?" after and collects user input to be used in the compute_total(earned,shifted, shift) function:

printf("Were scores shifted (1=yes, 2=no)? ");
    double shifted;
    scanf("%lf", &shifted);
    if(shifted == 1){
      printf("Shift amount? ");
      double(shift);
      scanf("%lf", &shift);
    }else{}

    double total = compute_total(earned, shifted, shift);

However, obviously I cannot access the variable inside of the if-statement, when I bring the variable and scanf for shift outside of the if scope then the program will run but as I enter a digit for shift amount the terminal does not go any further through my program, it gets "stuck".

How should I solve this issue so I can access the variable but still function correctly?

question from:https://stackoverflow.com/questions/65949776/how-to-access-a-variable-inside-of-an-if-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You probbaly want this:

printf("Were scores shifted (1=yes, 2=no)? ");
double shifted;
double shift = 0;      // declare shift here (and probably initialize to 0?)

scanf("%lf", &shifted);
if(shifted == 1){
  printf("Shift amount? ");
  scanf("%lf", &shift);
}else{}

double total = compute_total(earned, shifted, shift);

BTW: double(shift); is wrong and doesn't even compile. Did you retype your code instead of copy/pasting it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...