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