简体   繁体   English

当if(可变%2 == 0)时程序崩溃

[英]Program crashes when `if (variable % 2 == 0)`

I'm writing a program that finds perfect numbers . 我正在写一个寻找完美数字的程序。 Having read about these perfect numbers I came across a list of them: List of perfect numbers . 阅读这些理想数字后,我发现了其中的一个列表: 理想数字列表 At the moment the output is: 目前的输出是:

28         // perfect
496        // perfect
8128       // perfect
130816     // not perfect
2096128    // not perfect
33550336   // perfect

I decided to create array and put it with numbers, which divide the number wholly (without the rest). 我决定创建一个数组,并将其放入数字中,该数字将整个数字相除(不包括其余部分)。 So I will be able to verify if it is a perfect number or not by adding all elements of the array. 因此,通过添加数组的所有元素,我将能够验证它是否为完美数。 But app crashes and I cannot understand why: 但是应用程序崩溃了,我不明白为什么:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned long number;
    unsigned long arr2[100] = {0};
    int k = 0;

    for ( number = 0; number <= 130816; number++ )
        if ( 130816 % number == 0 )
            arr2[k++] = number;

    for ( k = 0; k < 100; k++ )
        printf("%lu", arr2[k]);

    return 0;
}

You are doing modulus zero here: 您在这里将模数设为zero

if ( 130816 % number == 0 )

which is undefined behavior. 这是未定义的行为。 If you start your for loop at 1 instead it should fix that issue. 如果您从1开始for循环,则应该可以解决该问题。 However, since N % 1 == 0 for all N , you probably need to start at 2 . 但是,由于所有N N % 1 == 0 ,您可能需要从2开始。

From the C99 standard, 6.5.5 /5 (unchanged in C11 ): 根据C99标准6.5.5 /5 (在C11更改):

The result of the / operator is the quotient from the division of the first operand by the second; /运算符的结果是第一个操作数除以第二个的商。 the result of the % operator is the remainder. %运算符的结果是余数。 In both operations, if the value of the second operand is zero, the behavior is undefined. 在这两个操作中,如果第二个操作数的值为零,则行为是不确定的。

You are dividing by zero when number=0; 当number = 0时,您被零除;

138816 % number involves division and a remainder. 138816 % number涉及除法和余数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM