首页 > 解决方案 > 要求输入数字直到输入零的算法

问题描述

我正在尝试在 C 中创建一个算法,要求您输入任何数字,并在您输入数字 0 时停止询问。我应该使用 while 循环来完成,但它不起作用,我尝试了一切我学过。这是我的代码不起作用:

#include<stdio.h>

int main()
{
    int number;
    while(number != 0)
    {
        printf("Introduce a number: ");
        scanf("%i",&number);
    }

    return 0;
}

标签: c

解决方案


希望现在把我的两分钱带到聚会上还为时不晚。

其他人建议的解决方案绝对是可能的并且可行的解决方案,但是,我认为它可以以稍微整洁的方式完成。对于这样的情况,do while存在语句:

#include <stdio.h>

int main() {
    int number; // Doesn't need to be initialized in this case
    do {
        printf("Introduce a number: ");
        if (scanf("%i", &number) != 1) { // If the value couldn't be read, end the loop
            number = 0;
        }
    } while (number != 0);

    return 0;
}

我认为这个解决方案更好的原因只是它没有给代码带来任何其他魔法常量,因此它应该更好地阅读。

例如,如果有人看到int number = 42;,他会问 - 为什么是 42?为什么初始值是 42?这个值是否在某处使用?答案是:不,它不是,因此没有必要在那里拥有它。


推荐阅读