C++控制台程序崩溃,没有任何错误

C++ console program crashes without any error

本文关键字:任何 错误 控制台 程序 崩溃 C++      更新时间:2023-10-16

我试图解决Project Euler的问题5,但程序崩溃,我没有得到任何错误:

#include <stdio.h>
#include <iostream>
using namespace std;
/* Problem 5:
    2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
    What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
*/
int selle(int number) {
    int c = 0;
    for (int i = 0; i <= 20; i++)
        if (number % i == 0)
            c++;
    return c;
}
int problem(int number) {
    while (number > 0) {
        if (selle(number) == 20)
            return number;
        number++;
    }
    return 404;
}
int main() {
    long long number = 2;
    cout << problem(number);
    system("PAUSE");
    return 0;
}

我认为问题出在第一个函数的"for"循环中,但我不知道它是什么。同时试图将函数设置为long-long也会发生这种情况。非常感谢。

for (int i = 0; i <= 20; i++)
    if (number % i == 0)
        c++;

i为零时(第一次迭代)。。。你正在除以零。。。这是不允许的。

这就是你的程序崩溃的原因。

问题是您在某个时刻执行number % 0。和被零除一样,被零取模也是不允许的。如果模运算中的第二个操作数为0,则会导致未定义的行为(http://en.cppreference.com/w/cpp/language/operator_arithmetic)。

顺便说一句,您可以从long long number = 20;开始,执行20的增量(number += 20;),因为您不会在两者之间找到任何匹配项。