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));
    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/

相关文章:

c++ - char vector 可以越界吗?

C++03 链接器 "already defined symbol"没有出现在中间文件中

c++ - 为什么 floor 不返回整数?

c++ - 构造函数与数组初始值设定项的歧义

c++ - 如何在 C++ 中拦截 ImageMagick 抛出的异常?

c++ - map中operator[]插入的指针类型的值是否总是NULL?

c++ - 实现简单的输入流

c++ - 为什么我的 IWMPEvents 函数从未被调用?

c++ - 使用 60K+ 条目初始化类静态映射

c++ - 绕过特定地址获取寄存器值【x86 assembly on Windows】