首页 > 解决方案 > for循环中的N模0返回C中的N?

问题描述

我正在编写一个 C 程序,我想在其中创建一个函数,该函数接受一个“n”整数,并返回它所具有的除数。

int divisors(int n) {
int amount = 0;
for(int i = 0; i <= n; i++) {
    printf("%d mod %d = %d\n", n, i, n % i);
    if(n % i == 0) {
        amount++;
    }
}

return amount;
}

printf 显然是用于调试的。会导致问题的代码部分是循环从 0 开始,这意味着在第一次迭代中,程序必须打印 N mod 0。但是,我只是通过将一些 int a 分配给该函数来测试该函数在 main() 中输入 8,程序会打印:

8 mod 0 = 8
8 mod 1 = 0
8 mod 2 = 0
8 mod 3 = 2
8 mod 4 = 0
8 mod 5 = 3
8 mod 6 = 2
8 mod 7 = 1
8 mod 8 = 0

所以 0 模数运行没有问题,而是返回 n 。有趣的是,如果我明确地告诉程序,printf("%d", 8 % 0);那么我会得到我期望的错误。那么有谁知道为什么 n mod 0 在循环中在 C 中运行时没有错误?

注意:该程序是用 GCC 编译的,编译时甚至不会抛出任何警告/错误。

编辑:添加 gcc --version。

配置: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1 Apple clang 版本13.0.0 (clang-1300.0.29.3) 目标:arm64-apple-darwin20.6.0 线程模型:posix InstalledDir:/Library/Developer/CommandLineTools/usr/bin

标签: cfunctionfor-loopdivisionmodulo

解决方案


当模运算符的第二个操作数为 0 时,行为未定义。你几乎可以从这个操作中得到任何结果,正如你所看到的,对于同一个操作,一次你得到 8,另一次程序终止。


推荐阅读