C++控制台程序崩溃,没有任何错误
C++ console program crashes without any error
我试图解决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;
),因为您不会在两者之间找到任何匹配项。
相关文章:
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- boost::p rogram_options 在指定意外的位置参数时不报告任何错误
- Antlr cpp 运行时 任何错误的指针转换?
- 我可以使用 try catch 语句来捕获任何错误而不是具体错误吗?
- 为什么 C++ 中的分号在插入代码开头时不显示任何错误?
- 如何修复任何错误
- 为什么<<低;和 cout<<v.begin;单独给出错误,但 cout <<(lower.begin());没有给出任何错误,并使代码易于编译
- 我是否需要处理以下代码中的任何错误情况?
- 我的代码在构建时没有任何错误,但无法正常工作
- 由于错误,c ++代码无法在Visual Studios上运行,但不显示任何错误
- ROS2 COLCON构建未在Windows中显示任何错误消息
- 如何调试 gRPC 服务器崩溃而没有任何错误
- 尝试使用类,但未打印任何内容.不会生成任何错误.我错过了什么吗?
- 代码没有任何错误,但什么也不在命令提示中
- GTK图像突然不会刷新任何错误或警告
- STL 中是否有任何错误代码异常
- 用“ strcpy”在2D数组中删除(字符)的一行(字符)时是否存在任何错误
- Oracle ODBC 插入失败,没有任何错误诊断
- 检查输入的文件是否有任何错误
- 带有绝对路径的LoadLibrary返回不正确的HMODULE,没有任何错误