gpt4 book ai didi

C 编程 - 循环直到用户输入数字 scanf

转载 作者:行者123 更新时间:2023-11-30 16:19:41 26 4
gpt4 key购买 nike

我需要帮助检查我的程序的错误。我要求用户输入一个整数,我想检查用户输入是否是一个整数。如果没有,请重复 scanf。

我的代码:

int main(void){

int number1, number2;
int sum;

//asks user for integers to add
printf("Please enter the first integer to add.");
scanf("%d",&number1);

printf("Please enter the second integer to add.");
scanf("%d",&number2);
//adds integers
sum = number1 + number2;

//prints sum
printf("Sum of %d and %d = %d \n",number1, number2, sum);

//checks if sum is divisable by 3
if(sum%3 == 0){
printf("The sum of these two integers is a multiple of 3!\n");
}else {
printf("The sum of these two integers is not a multiple of 3...\n");
}
return 0;
}

最佳答案

scanf 根据您的格式返回已成功读取的项目数。您可以设置一个仅当 scanf("%d", &number2); 返回 1 时退出的循环。然而,技巧是当 scanf 返回零时忽略无效数据,因此代码如下所示:

while (scanf("%d",&number2) != 1) {
// Tell the user that the entry was invalid
printf("You did not enter a valid number\n");
// Asterisk * tells scanf to read and ignore the value
scanf("%*s");
}

由于您在代码中多次读取数字,请考虑创建一个函数来隐藏此循环,并在 main 中调用此函数两次以避免重复。

关于C 编程 - 循环直到用户输入数字 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562274/

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