二进制%的操作数无效(有浮点数和浮点数)

时间:2015-11-17 13:36:59

标签: c modulo

以下是我的代码:

#include <stdio.h>

int main ( )   
{
    float a = 5,b = 2;    
    int c,d;    
    c = a % b;
    d = a/2;    
    printf("%d\n",d);    
    return 0;
}

当我尝试编译时,我得到了

  

“二进制%的操作数无效”

在第6行。我该如何解决这个问题?

5 个答案:

答案 0 :(得分:4)

 c = a % b;

您不能将float用作%运算符的操作数。

使用fmod中的math.h代替。

double a=5,b=2,c;
c=fmod(a,b);                 // it returns double

答案 1 :(得分:1)

正如其他人已经提到的那样,你对模运算符的操作数类型有疑问。您需要为模运算符设置类型为int的操作数。

添加一些引用,引用C11标准,章节§6.5.5,乘法运算符

  

[..] %运算符的操作数应为   有整数类型。

答案 2 :(得分:0)

您不能将模数(%)用于浮动参数。也许你想做:

    function getIP() {
    $ip = $_SERVER['SERVER_ADDR'];

    if (PHP_OS == 'WINNT'){
        $ip = getHostByName(getHostName());
    }

    if (PHP_OS == 'Linux'){
        $command="/sbin/ifconfig";
        exec($command, $output);
        // var_dump($output);
        $pattern = '/inet addr:?([^ ]+)/';

        $ip = array();
        foreach ($output as $key => $subject) {
            $result = preg_match_all($pattern, $subject, $subpattern);
            if ($result == 1) {
                if ($subpattern[1][0] != "127.0.0.1")
                $ip = $subpattern[1][0];
            }
        //var_dump($subpattern);
        }
    }
    return $ip;
}

答案 3 :(得分:0)

模数运算符%用于整数,您使用了浮点数。

您可以使用c = (int) a % (int) b; fmod(a,b)

答案 4 :(得分:0)

你确定它在第6行吗?它更可能成为

的界限

c = a % b;

因为%只需要整数值,而不是浮点数。如果你真的想要a和b是浮点数,你可能需要做一些演员。

相关问题