【问题标题】:How do I return to the Beginning of my Program without a Goto Statement如何在没有 Goto 语句的情况下返回程序开头
【发布时间】:2016-02-01 07:02:33
【问题描述】:
#include <stdio.h>
#include <math.h>

long factcalc(int num1);

int main(void) 
{
    int num1;
    long factorial;
    int d;
    int out;

    printf("Please enter a number that is greater than 0");
    scanf_s("%d", &num1);

    if (num1 < 0) {
        printf("Error, number has to be greater than 0");
    } else if (num1 == 0) {
        printf("\nThe answer is 1");
    } else {
        factorial = factcalc(num1);
        printf("\nThe factorial of your number is\t %ld", factorial);
    }

    return 0;
}

long factcalc(int num1) 
{
    int factorial = 1;
    int c;

    for (c = 1; c <= num1; c++)
    factorial = factorial * c;

    return factorial;
}

我想知道,如何让程序不断询问用户输入,直到用户输入“-1”?因此,即使在计算了一个数字的阶乘之后,它也会不断要求更多数字,直到用户输入 -1,当它显示错误消息等时也是如此。提前致谢。

【问题讨论】:

  • 为什么不使用循环?我认为不需要goto

标签: c function loops break


【解决方案1】:

通过引入无限循环很容易实现。

#include <stdio.h>
#include <math.h>

#ifndef _MSC_VER
#define scanf_s scanf
#endif

long factcalc(int num1);

int main(void)
{
    int num1;
    long factorial;
    int d;
    int out;

    for (;;) {
        printf("Please enter a number that is greater than 0");
        scanf_s("%d", &num1);
        if (num1 == -1) {

            break;
        }

        else if (num1 < 0) {

            printf("Error, number has to be greater than 0");
        }

        else if (num1 == 0) {

            printf("\nThe answer is 1");
        }

        else {

            factorial = factcalc(num1);
            printf("\nThe factorial of your number is\t %ld", factorial);
        }
    }

    return 0;
}

long factcalc(int num1) {

    int factorial = 1;
    int c;

    for (c = 1; c <= num1; c++)
        factorial = factorial * c;

    return factorial;
}

【讨论】:

    【解决方案2】:

    在少数情况下使用goto 是“可以的”,但这肯定不是一个。

    首先,将程序的相关部分放入函数中。

    然后,像这样监控和使用用户输入:

    int number = -1;
    
    while (scanf("%d", &number)) {
        if (-1 == number) {
            break;
        }
    
        call_foo_function(number);
    }
    

    【讨论】:

      【解决方案3】:

      是的,正如@ameyCU 所建议的,使用循环是解决方案。例如,

      while (1)
      {
          printf("Please enter a number that is greater than 0");
          scanf_s("%d", &num1);
      
          if (-1 == num1)
          {
              break;
          }
      
          // Find factorial of input number
          ...
          ...
      
          // Loop back to get next input from user
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-29
        • 1970-01-01
        • 2011-02-11
        • 1970-01-01
        • 2017-10-26
        • 1970-01-01
        • 2015-09-12
        • 2022-10-31
        相关资源
        最近更新 更多