You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言整数整除判断程序如何添加除数为0的错误提示逻辑?

C语言整除判断程序增加除数为0校验的实现方案

你需要优先对除数是否为0做前置判断,避免直接执行取模、除法运算触发程序崩溃,同时修正原代码中if块缺少闭合右大括号的语法问题,具体修改后的完整代码如下:

#include <stdio.h>

int main (void)
{
    int value1, value2, calculate = 0;
    
    printf("\nProgram should perform the following:\n");
    printf("\nHave the user enter two different integer numbers to be divided by the program ");
    printf("\nIf the division of both numbers\n");
    printf("\nresult with the remainder of zero,\n");
    printf("\nby the second number.\n");
    printf("Example: thirty-five divided by seven will have a remainder of zero\n");
    
    printf("Please enter the first integer number>>");
    scanf("%i", &value1);
    
    printf("Please enter the second integer>> ");
    scanf("%i", &value2);
    
    // 新增除数为0的前置判断
    if (value2 == 0) {
        printf("\n错误:除数不能为0,请输入合法的第二个整数\n");
    }
    // 除数合法时再判断是否可整除
    else if (value1 % value2 == 0) {
        printf("\n%i is evenly divisible by %i\n", value1, value2);
        calculate = value1 / value2;
        printf("%i / %i = %i\n", value1, value2, calculate);
    }
    // 处理不能整除的场景
    else {
        printf("\n%i is not evenly divisible by %i\n", value1, value2);
    }
    
    return 0;
}

逻辑说明

  • 优先级最高的判断是除数是否为0,只要第二个输入值为0直接输出错误提示,跳过所有运算逻辑,避免程序运行报错
  • 只有除数合法时,才会进入整除判断分支
  • 多分支使用else if和else串联,互斥执行,不会出现逻辑冲突

内容的提问来源于stack exchange,提问作者William Posey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:15:05