简体   繁体   English

在质数 C++ 程序中不断得到浮点异常

[英]Keep getting floating point exception in prime number c++ program

I am trying to create a program that takes a user integer and determines whether or not the integer is a prime number.我正在尝试创建一个程序,该程序采用用户整数并确定该整数是否为素数。 However, when I try to enter a number I get a floating point exception.但是,当我尝试输入一个数字时,出现浮点异常。 Why is that?这是为什么? I made an array in order to go through every number up until the integer to check its divisibility Here is the code:我制作了一个数组,以便遍历每个数字直到整数以检查其可整性这里是代码:

#include <iostream>
using namespace std;
bool isPrime(int n)
{
    int arr[n];
    if (n == 1 or n == 2) {
        return true;
    }
    for (int i = 1; i < n; i++){
        if (n % arr[i] == 0) {
            return false;
        }
        else {
             return true;
        }
    }
}
int main()
{
    int user_input;
    cout << "Enter an integer to test if it's prime: ";
    cin >> user_input;
    bool value = isPrime(user_input);
    string true_false;
    if (value == 1) {
        true_false = "true";
    }
    else {
        true_false = "false";
    }
    cout << true_false;
    return 0;
}

The fatal exception occurs in the line if (n % arr[i] == 0) { .致命异常发生在if (n % arr[i] == 0) { This array points to uninitialized memory, which will occasionally contain 0 resulting in a divide by zero error.此数组指向未初始化的内存,其中偶尔会包含 0,从而导致除以零错误。 Thanks to nm .感谢nm for pointing out my error.指出我的错误。

Using C idiom such as int arr[n];使用 C 习语,例如int arr[n]; where n is not a know constant at compile time is going to result in common C programming issues, like this.其中n在编译时不是已知常量会导致常见的 C 编程问题,就像这样。 C++ has features that can be used which avoid these problems. C++ 具有可用于避免这些问题的功能。 I recommend you study and use modern C++.我建议你学习和使用现代 C++。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM