c - 如何在没有 Goto 语句的情况下返回程序的开头

标签 c function loops break

#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 为止,当它显示错误消息等时也是如此。提前致谢。

最佳答案

可以通过引入无限循环轻松实现。

#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;
}

关于c - 如何在没有 Goto 语句的情况下返回程序的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459950/

相关文章:

swift - 显示 = brain.evaluateWithErrorReport(添加了使用 : dictionaryForVaribles) gives an error unless an as!。为什么?

python - 默认情况下,将参数设置为等于另一个参数的值

java - 出现意外的死循环

java - 语法问题 : Ternary and loop inside return statement

c - 在STM32上直接使用ODR寄存器

c - 尽管设置了 rfcomm 安全性,Bluez hcidump 仍然清晰

c - 在 Linux 中实现零页的最快方法

c - XC8 库组织和跨多个源文件的#defines

c++ - 通过引用 v. 通过指针传递——优点?

Node.js - 使用异步库 - 带有对象的 async.foreach