C++ 错误:二进制 % 的无效操作数(有“double”和“double”)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3902399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: invalid operands to binary % (have 'double' and 'double')
提问by pisfire
I have a program I am writing that lists 100,000 prime numbers. It works fine for 10 numbers, but after so many numbers they turn into negative values. I changed the ints to long ints and that did not change anything, then I changed them to doubles and I get the error listed in the title. What should my variable be? Keep in mind I am still new to programing. I also looked at some previous posts and did not see the answer.
我正在编写一个程序,它列出了 100,000 个素数。它适用于 10 个数字,但在这么多数字之后它们变成负值。我将整数更改为长整数并且没有任何改变,然后我将它们更改为双精度并且我得到了标题中列出的错误。我的变量应该是什么?请记住,我对编程还很陌生。我也看了一些以前的帖子,没有看到答案。
int is_prime(double x,char array[]){
//doesnt use array but I put it in there
double j=2;//divider
for(j=2;j<=pow(x,0.5);j++){
if((x%j==0)){
return(0);
} //isnt prime
}
return(1);// because it is prime.
}
回答by
You can't use a double with the operator, you must have an int.
您不能将 double 与运算符一起使用,您必须有一个 int。
You should: #include <math.h>
and then use the fmod function.
您应该:#include <math.h>
然后使用 fmod 函数。
if(fmod(x,j)==0)
Full code:
完整代码:
#include <math.h>
int is_prime(double x,char array[]){
//doesnt use array but I put it in there
double j=2;//divider
for(j=2;j<=pow(x,0.5);j++){
if(fmod(x,j)==0){
return(0);
} //isnt prime
}
return(1);// because it is prime.
}
回答by Mark Elliot
You have two options:
您有两个选择:
Stick with the
%
operator, then you're required to cast the inputs toint
sif(((int)x % (int)j) == 0)
Include
math.h
and then usefmod
:if(fmod(x, j) == 0)
坚持使用
%
运算符,然后您需要将输入转换为int
sif(((int)x % (int)j) == 0)
包括
math.h
然后使用fmod
:if(fmod(x, j) == 0)
回答by Jon Hanna
Your immediate question can be solved with fmod
, but for your purpose of high-value prime numbers, you may be better off looking at a big-integer class, like that at http://sourceforge.net/projects/cpp-bigint/since what you really want is integer mathematics, and using floats might cause problems as things progress.
您的直接问题可以用 解决fmod
,但是为了您的高价值素数的目的,您最好查看一个大整数类,例如http://sourceforge.net/projects/cpp-bigint/因为你真正想要的是整数数学,随着事情的进展,使用浮点数可能会导致问题。