错误 C2296:'%':非法的左操作数在 C++ 中具有类型 'double'

error C2296: '%' : illegal, left operand has type 'double' in C++

本文关键字:C++ 类型 double C2296 非法 错误 操作数      更新时间:2023-10-16

我必须使用带双数字的"%",但在C++中它不起作用。示例:

double x;
temp = x%10;

我得到这个错误:

error C2296: '%' : illegal, left operand has type 'double' 

如何在不将数字从二重转换为整数的情况下解决此问题?如果我转换它,我会丢失小数部分,我不想要。

还有其他选择吗?

%不是为双打定义的,但您可以使用fmod

计算除法余数返回numer/denom的浮点余数(向零取整):

示例(适用于C++)来自http://www.cplusplus.com/reference/cmath/fmod/:

#include <cmath>       /* fmod */
#include <iostream>
int main ()
{
  std::cout << "fmod of 5.3 / 2 is " <<  std::fmod (5.3, 2) << std::endl;
  return 0;
}

使用fmod函数

#include <math.h>
double x;
temp = fmod(x, 10.0);