获取错误浮点异常

获取错误浮点异常

本文介绍了获取错误浮点异常:8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么g ++不喜欢我的代码。它在java中运行良好。非常感谢任何见解。

I have no idea why g++ doesn't like my code. It ran fine in java. Any insights would be greatly appreciated.

#include<iostream>

using namespace std;

bool isPrime(long number);

int main(){
const long number = 600851475143;
long max = 0;
for(long i= 0; i*i <= number; i++)
    if(number % i == 0 && isPrime(i))
        max = i;
cout<< max << endl;

return 0;
}

bool isPrime(long number){
if(number <= 1) return false;
if(number == 2) return true;
if(number % 2 == 0) return false;

for(long     i= 3; i*i <= number; i+=2)
    if(number % i == 0)
        return false;
return true;
}


推荐答案

const long number = 600851475143;

有溢出,长不能持有大数字。

There is overflow, long can't hold that big number.

请参阅

LONG_MAX is 2147483647

try:

const unsigned long long number = 600851475143;
unsigned long longmax = 0;

编辑:

%对0, i 0开始

for(long i= 0; i*i <= number; i++)
           ^^
{
    if(number % i == 0 && isPrime(i))
               ^^^
{
   max = i;
   cout<< max << endl;
}

}

轻微更改为正常版本:

bool isPrime(unsigned long long  number);

int main(){

    const unsigned long long number = 600851475143;
    unsigned long long max = 0;
    for(long i = 1; i*i <= number; i++)
    {
        if(number % i == 0 && isPrime(i))
        {
            max = i;
            cout<< max << endl;
        }
    }
    return 0;
}

bool isPrime(unsigned long long  number)
{
    if(number <= 1) return false;
    if(number == 2) return true;
    if(number % 2 == 0) return false;

    for(unsigned long long i= 3; i*i <= number; i+=2)
    {
        if(number % i == 0)
        {
            return false;
        }
    }
    return true;
}

这篇关于获取错误浮点异常:8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 17:44