使用字符输入执行while循环

时间:2016-11-14 09:21:39

标签: c char do-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中运行此代码。

3 个答案:

答案 0 :(得分:3)

只需修改您的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

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

答案 1 :(得分:2)

你的倒数第二行有一个字符串文字"y",它应该是一个字符文字,即'y'

 } while (choice =="y" || choice =="Y");

这应该是:

 } while (choice =='y' || choice =='Y');

此外,您的scanf()不会消耗空白。在%c之前添加一个空格,使其忽略换行符或其他空格:

scanf(" %c", &choice);

答案 2 :(得分:0)

即使在修正后仍尝试执行以下操作,但代码中仍存在一些错误 如果您输入&#39; Y&#39;并重新计算一个因子,它给出了错误的答案

  

int factorial已经加载了前一个值

#include "stdafx.h"
#include <stdio.h>
#include <iostream>

using namespace System;
using namespace std;

int calculateFactorial(int i);

int main()
{
    int i;
    char choice;

    do{
        printf("Enter the no whose factorial you want to calculate:\t");
        scanf("%d", &i);
        printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
        printf("\n Do you want to continue (Y/N)?");
        scanf(" %c", &choice);
    } while (choice == 'y' || choice == 'Y'); 
    return 0;
}

int calculateFactorial(int i) {
    int factorial = 1;
    if (i == 0){
        factorial = 1;
    }else {
        while (i > 0){
            factorial = factorial*i;
            i--;
        }
    }
    return factorial;
}