这是问题。
编写一个程序,要求用户输入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/

10-11 21:02
查看更多