0
我不明白为什么我的程序运行正常,然后当做...当重复它进入我的其他功能,当我不想要它。完成后,我的程序就会像我想要的那样重复。对于糟糕的解释我很抱歉,但我认为“我的计划”下面的图片比我能解释发生的事情要好。我不明白为什么我的C程序正确运行一次,然后给我不想要的结果
#include <stdio.h>
#include <stdlib.h>
int main()
{
float fahrenheit,celsius;
char selection[30];
char *idontknow;
long trueselection;
do{
printf("1: Fahrenheit to Celsius.");
printf("\n2: Celsius to Fahrenheit.");
printf("\n3: Quit program.\n");
fgets(selection,10,stdin); //This line and the line below are in the program
//so that if the user inputs a character instead of an integer it does not infinite loop.
trueselection = strtol(selection, &idontknow, 10);
if(trueselection==1){
printf("Enter temperature in Fahrenheit: ");
scanf("%f",&fahrenheit);
celsius= (fahrenheit - 32)/1.8;
printf("Temperature in Celsius: %.2f\n\n\n",celsius);
}
else if(trueselection==2){
printf("Enter temperature in Celsius: ");
scanf("%f",&celsius);
fahrenheit= (celsius*1.8)+32;
printf("Temperature in Fahrenheit: %.2f\n\n\n",fahrenheit);
}
else if(trueselection==3){ //This "else if" statement is so the program does not say invalid selection before exiting if 3 is entered.
return 0;
}
else{
printf("Invalid selection !!!\n\n\n");
}
}
while(trueselection!=3); //This line tells the program to repeat back to line 3 if any selection but 3 is selected.
}
对不起,我仍然有一个很难理解一点点。所以fgets()从我的if语句中读取\ n? – RyanK
Nvm,谢谢你BLUEPIXY这是我第一次编程任何计算机语言后的第三个星期,我很难理解这个网站上的术语,但是在重新阅读了你多次给出的重复链接后,我终于明白了我无法混合使用scanf()和fgets()。 – RyanK