程序崩溃时,如果`(可变%2 == 0)` [英] Program crashes when `if (variable % 2 == 0)`

查看:178
本文介绍了程序崩溃时,如果`(可变%2 == 0)`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写认定的程序完美数的。 完美数的清单:看了这些的完美数的我碰到他们的名单出来。此刻的输出是:

  28 //完美
496 //完美
8128 //完美
130816 //不完美
2096128 //不完美
33550336 //完美

我决定创建数组并把它与数字,这完全把数(不休息)。因此,我将能够验证,如果它是一个的完美的号码或不加入数组的所有元素。但是,应用程序崩溃,我不明白为什么:

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释的main()
{
    无符号长一些;
    无符号长ARR2 [100] = {0};
    INT K = 0;    为(数= 0;数字&下; = 130816;数++)
        如果(130816%数== 0)
            ARR2 [K +] =号;    对于(K = 0; K< 100; k ++)
        的printf(%禄,ARR2 [K]);    返回0;
}


解决方案

您正在做的模量这里:

 如果(130816%数== 0)

这是不确定的行为。如果您在 1 启动for循环,而不是它应该解决这个问题。然而,由于 N%1 == 0 所有 N ,你可能需要在 2 。

C99 标准, 6.5.5 / 5 (在 C11 不变):


  的 /操作的结果是从第一个操作数由相除所得的商
  第二; %操作的结果是余数。在两个操作中,如果该值
  第二个操作数是零,则行为是不确定的。


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:

if ( 130816 % number == 0 )

which is undefined behavior. If you start your for loop at 1 instead it should fix that issue. However, since N % 1 == 0 for all N, you probably need to start at 2.

From the C99 standard, 6.5.5 /5 (unchanged in 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.

这篇关于程序崩溃时,如果`(可变%2 == 0)`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆