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

What is wrong with this expression? "if (factorarray[x]%2 == 0 && factorarray[x]%3 ==0..."

本文关键字:factorarray if 什么 问题      更新时间:2023-10-16

代码如下:

#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'无效的操作数&长双"

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

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

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

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

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

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