错误:二进制%的操作数无效(有'double'和'double')

pis*_*ire 6 c c++

我有一个我写的程序,列出了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.
 }
Run Code Online (Sandbox Code Playgroud)

小智 14

你不能在运算符中使用double,你必须有一个int.

您应该:#include <math.h>然后使用fmod函数.

if(fmod(x,j)==0)
Run Code Online (Sandbox Code Playgroud)

完整代码:

 #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.
 }
Run Code Online (Sandbox Code Playgroud)


Mar*_*iot 7

您有两个选择:

  1. 坚持使用%运算符,然后您需要将输入转换为ints

    if(((int)x % (int)j) == 0)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 包含math.h然后使用fmod

    if(fmod(x, j) == 0)
    
    Run Code Online (Sandbox Code Playgroud)