【问题标题】:Prompt the user to ask the input until the condition is met?提示用户询问输入,直到满足条件?
【发布时间】:2019-03-02 01:28:48
【问题描述】:
int32_t number;
uint32_t x = 1;

puts("What number do you want to count: ?");
{
    scanf("%i", &number);
    printf("You typed%i.\n", number);
    while(x < number) {
        printf("%i and then \n", x);
        x++;
    }
    if (x > 100 || x < 1)
        printf("error");
}

我想打印所有数字,直到用户输入数字。但是如果输入的数字小于 1 或大于 100,那么它应该说错误并要求用户再次输入数字,但它不会这样做。例如,如果数字是 455,它应该说错误并提示用户再次输入数字。上面的程序仅在分别打印所有偶数或小于 100 和 1 的数字后才打印错误。

【问题讨论】:

  • 为什么要比较 uint32_t 和 int32_t?
  • edit您的问题并显示输入和预期输出的示例。
  • 我首先要打消你的假设,即scanf 总是有效的。它有一个返回结果是有原因的;用它。不要忽视它。
  • 另外,不是说当你在scanf中使用%i时,如果输入(010->十进制的8)它可以读取八进制和十六进制数

标签: c loops do-while counting


【解决方案1】:
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    int32_t number;

    while (puts("What number do you want to count? "),  // prompt the user
           scanf("%i", &number) != 1                    // reading an int failed
           || number < 1 || 100 < number)               // number not in range
    {
        fputs("Error!\n\n", stderr);       // print an error message
        int ch;
        while ((ch = getchar()) != EOF && ch != '\n');  // remove garbage left in stdin
    }

    printf("You typed %d.\n", number);

    for(int32_t i = 0; i < number; ++i)
        printf("%i and then\n", i);
}

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多