[英]error: invalid operands to binary % (have 'double' and 'double')
I have a program I am writing that lists 100,000 prime numbers. 我有一个我写的程序,列出了100,000个素数。 It works fine for 10 numbers, but after so many numbers they turn into negative values. 它适用于10个数字,但在这么多数字之后它们变成负值。 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. 我将int更改为long int并且没有改变任何内容,然后我将它们更改为double,我得到标题中列出的错误。 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. 我还看了一些以前的帖子,但没有看到答案。
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.
}
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.
}
You have two options: 您有两种选择:
Stick with the %
operator, then you're required to cast the inputs to int
s 坚持使用%
运算符,然后您需要将输入转换为int
if(((int)x % (int)j) == 0)
Include math.h
and then use fmod
: 包括math.h
然后使用fmod
:
if(fmod(x, j) == 0)
您的直接问题可以通过fmod
解决,但是出于高价素数的目的,您最好还是查看一个大整数类,比如http://sourceforge.net/projects/cpp-bigint/因为你真正想要的是整数数学,并且随着事情的发展,使用浮点数可能会导致问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.