Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 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 Reply

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...