如果偶数浮点数(分数数)的模数为 2,那么它不会给出'0'结果!在C++

if the even float number ( fraction number) is modulus by 2 then it does not give '0' as result! in C++

本文关键字:C++ 结果 数数 浮点数 如果      更新时间:2023-10-16
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x;
cin>> x;
cout<< fmod(x,2.00);
}

如果我给出输入数字为 2.4,它给出一个输出:0.4。如何获得输出 0.00?

只有整数可以是偶数或奇数,像 2.4 这样的实数既不是奇数也不是偶数。如果要测试浮点数的整数部分是偶数还是奇数,可以将其转换为整数类型(这将截断小数部分(并使用%

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x;
cin >> x; // you should check that cin is good!
cout << (static_cast<int>(x) % 2) << endl;
}

您应该尝试,检查并适当处理的一些事情:

  • 负数
  • 呼啰啦啦数字
  • 非数字