我正在开发一个允许用户练习除法的程序。我的代码如下:
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
return main();
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
return main();
}
return 0;
}
基本上,它应该做的是首先选择两个随机数。然后,它应该检查第二个数字 (div2) 是否大于第一个 (div1),如果是,它将切换它们。然后,它会使用模数 (div1%div2) 来确保两个数可以相互相除而没有余数。如果不能无余除则重新启动程序(return main();)。但是,每当我运行它时,我都会收到段错误:核心已转储,无论是在我启动它时还是在运行几次之后。有想法该怎么解决这个吗?
谢谢!!
最佳答案
这是我在评论中所说的示例。显然,您可以重构它以使其更优雅地工作(截至目前,它有时会给您浮点异常),但它让您了解如何在不再次调用 main 的情况下执行此操作。
注意:您不需要为 NEWLINE 设置常量。 std 中已经有一个内置常量。事实上,您已经在使用该常量 (endl)。所以你可以只做 cout << endl 而不是 cout << NEWLINE。
//div1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
using namespace std;
#define CLS "\033[2J\033[1;1H"
#define NEWLINE "\n"
int main() {
while(true) {
srand(time(NULL));
int a, div1, div2;
div1=rand()%11;
div2=rand()%11;
while (div2>div1) {
swap(div1,div2);
continue;
}
if (div1%div2!=0) {
} else {
cout << CLS;
cout << NEWLINE;
do {
cout << div1 << " / " << div2 << " = ?" << endl;
cin >> a;
cout << CLS;
cout << NEWLINE;
cout << "\t\tWrong!!" << endl;
cout << NEWLINE;
} while (a!=div1/div2);
cout << CLS;
cout << NEWLINE;
cout << "\t\tCorrect!!" << endl;
cout << NEWLINE;
cout << "Hit enter to continue." << endl;
cin.ignore();
cin.get();
}
}
return 0;
}
关于c++段错误(核心转储)与模数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130452/