0

这是代码:

#include <iostream>
#include <ctype.h>
#include <iomanip>


using namespace std;

class Project3
{
public:
    void factorcalc()
    {
        while (i<5000000){
            ++i;
            factor = prime/i;
            if (factor == (long long int)factor){
            //if (modf(primeoverthree, 0) == 0){
                cout << "Factor is: " << setprecision(12) << factor << endl;
                cout << "Denominator is: " << setprecision(12) << i << endl;

                ++x;
                factorarray[x] = factor;
            }
            else{/*empty else statement*/}
        }
    }
    void displayfactorresults ()
    {
        for (x=0; x<9; ++x)
            if (factorarray[x]%2 == 0 && factorarray[x]%3 == 0 && factorarray[x]%5 == 0 && factorarray[x]%7 == 0){
            cout << factorarray[x] << setprecision(12) << endl;
            }
    }
private:
    long double factor = 1;
    long double prime = 600851475143;
    long double i = 0;
    int x = 0;
    long double factorarray[9];
};


int main() {
    Project3 Pro3;
    Pro3.factorcalc();
    Pro3.displayfactorresults();

    return 0;
}

该代码是对 projecteuler.net 上的项目 3 的响应。我正在尝试使用 c++ 和常识的基本知识来找到 600851475143 的最大素数。

函数中发生错误void displayfactorresults

编译器输出错误信息:

“二进制表达式'long-double'和'long-double'的无效操作数”

4

3 回答 3

4

%余数运算符只能应用于整数操作数。

factorarray[x]是类型long double,浮点类型。

使用该fmod函数(注意舍入错误!)或将操作数转换为整数类型。

或者,更好的是,factorarray首先创建一个足够大的整数类型的数组。您已经假设这些值可以转换为long long int. 将某些东西转换为所需的类型通常不如首先使用所需的类型。

于 2015-05-20T01:45:31.800 回答
1

factorarray是一个双打数组。不能对 使用模 ( %) double。在使用它之前将其转换为数组int或强制转换数组元素((int)factorarray[x]) % 2 == 0

于 2015-05-20T01:45:14.843 回答
1

factorarray[x] % 2 == 0(double type % 2 == 0) 没有意义,因为提醒永远不会是 0,当然编译器也不允许这样做。

于 2015-05-20T05:51:26.677 回答