这个表达有什么问题? "if (factorarray[x]%2 == 0 && factorarray[x]%3 ==0..."

What is wrong with this expression? "if (factorarray[x]%2 == 0 && factorarray[x]%3 ==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 函数中出现错误。

编译器输出错误信息:

"invalid operands to binary expression 'long-double' & 'long-double'"

factorarray 是双精度数组。您不能在 double 上使用模数 (%)。要么将其转换为 int 的数组,要么在使用之前转换数组元素 ((int)factorarray[x]) % 2 == 0

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

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

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

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

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