我正在学习c语言编程初学者。在while循环阶段,我正在尝试使用while循环程序来验证用户输入是否符合我的期望,除了一件事情是每当用户输入无效值循环终止并且我试图保持这种状态时询问用户,直到从用户那里获得有效值为止。这是我正在处理的代码。有人可以引导我进行操作吗?
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num;
int sum;
bool flag = 0;
printf("Enter the value GREATER than 20 and LESS than 25: ");
scanf("%d", &num);
while ( num > 20 && num < 25 ) {
sum += num;
num++;
}
if ( num < 20 || num > 25){
flag = 0;
printf("Invalid\n");
}
else
printf("sum of your number is : %d \n", sum);
return 0;
}
答案 0 :(得分:0)
您需要在while循环中使用scanf来通过不断询问来从用户那里获取正确的值。一旦获得正确的值,就不需要if条件来检查值的正确性,因为while循环仅在获得正确的值后退出。
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num = 0;
int sum = 0;
bool flag = 0;
printf("Enter the value GREATER than 20 and LESS than 25: ");
scanf("%d", &num);
while ( num < 20 || num >25 )
{
printf("Invalid number,Enter the value GREATER than 20 and LESS than 25: ");
scanf("%d", &num);
}
while ( num <= 25 )
{
sum += num;
num++;
}
printf("sum of your number is : %d \n", sum);
return 0;
}