我已经写了这个简单的程序,它应该计算由用户输入的数字的阶乘。程序应该要求用户停止或继续该程序以查找新数字的阶乘。做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它在推荐。我应该删除标签吗? –