这个表达有什么问题? "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
函数出错。
编译器输出错误消息:
"二进制表达式'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,当然编译器不允许这样做。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 以在Qt中的IF语句中设置时间延迟
- 这个表达有什么问题? "if (factorarray[x]%2 == 0 && factorarray[x]%3 ==0..."