我已經寫了這個簡單的程序,它應該計算由用戶輸入的數字的階乘。程序應該要求用戶停止或繼續該程序以查找新數字的階乘。做while循環與字符輸入
由於大多數時間用戶不注意CapsLock程序應該接受Y或Y作爲回答。但是每次運行這個程序,即使我輸入Y/Y,它都會被終止!
我用Google搜索,發現了這個問題可能是由於new line
字符得到我的字符輸入接受的話,我修改了scanf函數代碼scanf("%c", &choice);
到scanf("%c ", &choice);
,以適應新的行字符,但我的程序還是會被終止接受Y/Y作爲輸入後。
這是代碼。請儘可能讓我知道處理這些問題的最佳做法和方法以及所需的更正。
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
我在編程初學者,我在Visual Studio中運行該代碼2015
' } while(choice ==「y」||選擇==「Y」);' - >'} while(choice =='y'|| choice =='Y');' –
'「Y」'是指向'char'的指針,但是'Y ''僅僅是'char'。 – ForceBru
@Biffen它在推薦。我應該刪除標籤嗎? –