gpt4 book ai didi

c - 提示用户询问输入直到满足条件?

转载 作者:行者123 更新时间:2023-11-30 14:46:10 25 4
gpt4 key购买 nike

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 的数字后才打印错误。

最佳答案

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

关于c - 提示用户询问输入直到满足条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52514847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com