c - 循环内出现错误消息?

标签 c

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

相关文章:

c - 如何在ubuntu中将c程序设置为守护进程?

c - 在 QNX 上调试宏相关错误

c - 如何从默认的 gcc 搜索路径中删除路径

c - 如何将 CvMat 从类型 CV_AA 转换为 CV_32F

c - 不支持的 16 位应用程序

c - 使用 AES 新指令集解密时出现错误结果

c++ - NCURSES:创建没有循环的标题栏

c - 缺少 libgcc_s_dw2-1.dll

c - 如何替换文件中特定人物的字符串

c - stm32f100RB中定时器6或定时器7如何使用?