使用字符输入进行 while 循环

Ris*_*kla -1 c char do-while

我写了这个简单的程序,它应该计算用户输入的数字的阶乘。程序应该要求用户停止或继续程序以找到新数的阶乘。

由于大多数时候用户不注意 CapsLock,程序应该接受 Y 或 y 作为是的答案。但是每次我运行这个程序时,即使我输入 Y/y ,它也会被终止!

我用谷歌搜索并发现问题可能是由于new line字符被我的字符输入所接受,所以我修改了 scanf 代码从scanf("%c", &choice);toscanf("%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 

}
Run Code Online (Sandbox Code Playgroud)

我是编程初学者,我正在 Visual Studio 2015 中运行此代码。

dev*_*per 5

只需修改您的 scanf 如下:

printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
Run Code Online (Sandbox Code Playgroud)

你也应该使用:

} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
Run Code Online (Sandbox Code Playgroud)

注意:单引号'用于字符,双引号"用于字符串