C++ c++;带模数的分段断层(岩芯倾倒)
我正在开发一个允许用户练习除法的程序。我的代码如下:C++ c++;带模数的分段断层(岩芯倾倒),c++,C++,我正在开发一个允许用户练习除法的程序。我的代码如下: //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));
//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;
}
//div1
#包括
#包括
#包括
#包括
使用名称空间std;
#定义CLS“\033[2J\033[1;1H”
#定义换行符“\n”
int main(){
srand(时间(空));
INTA,第1部分,第2部分;
div1=rand()%11;
div2=rand()%11;
而(div2>div1){
掉期(第1分部、第2分部);
继续;
}
如果(div1%div2!=0){
返回main();
}否则{
cout这是我在评论中所说的一个例子。显然,您可以重构它,使它工作得更优雅(到目前为止,它有时会给您浮点异常),但它让您知道如何在不再次调用main的情况下实现这一点
注意:您不需要为换行符设置一个常量。std中已经有一个内置常量。事实上,您已经在使用该常量(endl)。所以您可以只执行cout操作。此代码可能会出现“除以0”错误。这就是为什么会出现此错误的原因
行“if(div1%div2!=0){”似乎是错误的。
在这一行中,如果div2==0,那么您的代码将崩溃。returnmain();
请不要这样做。那么我应该使用什么?system()调用?returnmain()基本上是再次对main进行递归调用,这将使您陷入无限循环,最终将溢出堆栈。因此,分段错误。您的程序需要连续结束或循环,但通常(不是通过递归调用,因为这将溢出堆栈)取决于您尝试执行的操作。好的,我可以转储return main()。但是,如果模数(div1%div2!=0)的部分失败,我应该使用什么来重新启动程序?而不是重新启动程序,请使用一段时间(true)然后编写程序,使其可以连续循环而不再次调用自身。这是不正确的。除零确实是未定义的,但不会导致崩溃。您可以很容易地对此进行测试。编写一个除0的程序。编译器会在您编译它时向您发出警告,但在您实际运行它时不会崩溃。警告Well看起来像这样:test.cpp:12:10:警告:除零未定义[-Wdivision by zero]
@EdwardL。据我所知,当你用除法0运行程序时,你会得到SIGFPE错误,程序会终止。我想它可能是编译器/系统特定的。我在clang-600.0.57下对此进行了测试,当用这个版本编译时它不会崩溃,我将尝试验证GNU编译器会做什么。看起来GNU编译器的行为与Clang编译器稍有不同,并且会终止。但是,两者都会在编译过程中发出警告。无论如何,这不是其分段错误的原因。这是由对main()的递归调用引起的.我做了一些不同的事情,但总的思路是一样的,而且似乎很有效。谢谢!
//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;
}