这就是问题所在。 编写一个程序,要求用户输入 1 - 5 之间的数字。您的程序应显示 1 - 20 之间所有能被该数字整除的数字。您将需要使用循环。
我想在用户输入超出范围的数字时输入错误消息,但我只是不知道该怎么做,或者把它放在哪里。 这是到目前为止我的代码,它将允许用户输入任何数字。
#include<stdio.h>
main()
{
int num = 0;
int i = 0;
printf("Please enter a number from 1 to 5\n");
scanf("%d",&num);
for(i>=1; i<=20; i++)
{
if(i %num == 0)
{
printf("%d",i);
} //end if
}//end loop
}//end main()
最佳答案
您只需要添加一个额外的条件来检查给定值是否在范围内。
#include<stdio.h>
int main()
{
int num = 0;
int i ; // There is no need to intialize variable.
printf("Please enter a number from 1 to 5\n");
scanf("%d",&num);
if( num >=1 && num <= 5)
{
for(i=1; i<=20; i++)
{
if(i %num == 0)
{
printf("%d",i);
} //end if
} // end for
} //end if
else
{
printf("Error Message\n");
}
}
关于c - 循环内出现错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26551765/