[英]Invalid operands to binary expression ('double(*)(double' and 'double')
[英]error: invalid operands to binary % (have 'double' and 'double')
我有一個我寫的程序,列出了100,000個素數。 它適用於10個數字,但在這么多數字之后它們變成負值。 我將int更改為long int並且沒有改變任何內容,然后我將它們更改為double,我得到標題中列出的錯誤。 我的變量應該是什么? 請記住,我仍然是編程的新手。 我還看了一些以前的帖子,但沒有看到答案。
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.
}
你不能在運算符中使用double,你必須有一個int。
您應該: #include <math.h>
然后使用fmod函數。
if(fmod(x,j)==0)
完整代碼:
#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.
}
您有兩種選擇:
堅持使用%
運算符,然后您需要將輸入轉換為int
if(((int)x % (int)j) == 0)
包括math.h
然后使用fmod
:
if(fmod(x, j) == 0)
您的直接問題可以通過fmod
解決,但是出於高價素數的目的,您最好還是查看一個大整數類,比如http://sourceforge.net/projects/cpp-bigint/因為你真正想要的是整數數學,並且隨着事情的發展,使用浮點數可能會導致問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.