我编写了这个简单的程序,它应该计算用户输入的数字的阶乘。程序应要求用户停止或继续程序,以便找到新数字的阶乘。
由于大多数时候用户不注意 CapsLock,程序应该接受 Y 或 y 作为"is"的答案。但是每次我运行这个程序时,即使我输入 Y/y ,它也会被终止!
我用谷歌搜索,发现问题可能是由于我的字符输入接受了换行
字符,因此,我修改了 scanf("%c", &choice) 中的 scanf 代码;
到 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 中运行此代码。
最佳答案
只需修改你的 scanf 如下:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
您还应该使用:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
注意:
单引号 '
用于字符,双引号 "
用于字符串
关于c - 使用字符输入执行 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585304/