【问题标题】:How to make a loop continuously keep asking for user input until a given character is entered that stops the program?如何使循环不断地询问用户输入,直到输入停止程序的给定字符?
【发布时间】:2022-09-29 04:05:50
【问题描述】:

我有这个程序:

int main(void){
    int x, number, factorial;

// The objective of this program is to compute the factorial
// for a user inputted number, stopping once \"-1\" is entered.

    printf(\"Please enter a positive number for factorial calculation (-1 to end) :\");
    scanf(\"%d\", &number);
        
    for (x = 1; x <= number; x++){
        factorial *= x;
        if (x == -1){
            break;
        }
    }   
    printf(\"factorial for %d is %d\", number, factorial);
    
    
}

应该像这样输出:

Please enter a positive number for factorial calculation (-1 to end) :4
factorial for 4 is 24
Please enter a positive number for factorial calculation (-1 to end) :6
factorial for 6 is 720
Please enter a positive number for factorial calculation (-1 to end) :8
factorial for 8 is 40320
Please enter number for factorial calculation (-1 to end) :-1

但我不断得到这个(在两次不同的运行中):

Please enter a positive number for factorial calculation (-1 to end) :4
factorial for 4 is 24

Please enter a positive number for factorial calculation (-1 to end) :-1
factorial for -1 is 1

我怎样才能让它继续要求更多的数字,直到我输入-1?另外,为什么在这里输入 -1 给我它的阶乘而不是停止循环?

  • 语言不是c#,应该是c/c++...

标签: c


【解决方案1】:

您可以将阶乘计算包装在这样的循环中:

    int number;
    int factorial = 1;
    while(true) {
        printf("Please enter a positive number for factorial calculation (-1 to end) :");
        scanf("%d", &number);
        if (number == -1)
            break; // or just return as you need
        for (x = 1; x <= number; x++){
            factorial *= x;
        }   
        printf("factorial for %d is %d", number, factorial);
        factorial = 1;
    }

在这种情况下,您将收到数字作为输入,然后开始检查用户输入的内容。

在您的代码中,您在 for 循环中检查 x 变量是否不同于 -1,但是当您开始循环时将 1 分配给 x 时,永远不会满足该条件。在这种情况下,您应该检查number,但这并不完全正确。

【讨论】:

    【解决方案2】:

    使用While loop 并检查用户输入后的值,看看是否需要跳出循环:

    int main(void){
        int x, number, factorial;
    
    // The objective of this program is to compute the factorial
    // for a user inputted number, stopping once "-1" is entered.
     
        while (true){
            printf("Please enter a positive number for factorial calculation (-1 to end) :");
            scanf("%d", &number);
            
            if (number == -1){
                break;
            }
            for (x = 1; x <= number; x++){
                factorial *= x;                
            }   
            printf("factorial for %d is %d", number, factorial);
        }
        
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      相关资源
      最近更新 更多