测试数字是否具有不带任何库的十进制值
问题描述:
我需要测试C ++中数字是否具有十进制值.我只想使用< iostream>
而没有其他库,但是我很好奇我使用的方法是否可以接受.如果您能提供任何帮助,找到更好的方法,那将是很好的.
I need to test if a number has a decimal value in C++. I only want to use <iostream>
and no other library, but I'm curious if the method I'm using would be acceptable. If you can offer any assistance finding a better way that would be great.
#include <iostream>
int main() {
double x, y;
std::cin >> x;
int z = x;
if (x - z != 0) {
std::cout << "It's a decimal.";
}
else {
std::cout << "It's not a decimal.";
}
return 0;
}
考虑了更长的时间后,我想出了一个新的函数,该函数似乎更容易接受.
Upon thinking about this longer, I came up with a new function that seems more acceptable.
double TestForDecimal(double Num) {
double z;
while (Num > 1) {
if (Num > 101) /* Increments down to 1 more quickly */ {
Num = Num - 100;
}
else if (Num > 12) { Num = Num - 10; }
else { Num--; }
}
if (Num < 1 && Num > 0) {
std::cout << "This number has a decimal value" << std::endl;
return 1;
}
else {
std::cout << "Theres no decimal" << std::endl;
return 0;
}
}
答
两种正确"的测试方法:
Two "correct" ways to test:
- 使用
std :: fmod(x,1.0)
隔离分数. - 使用
floor
或ceil
或trunc
丢弃分数,例如测试是否x == std :: floor(x)
.
- Isolate the fraction with
std::fmod(x, 1.0)
. - Discard the fraction using
floor
orceil
ortrunc
, e.g. test whetherx == std::floor(x)
.
一种不正确的方法:
- 对于超出目标类型范围的数字,强制转换为整数类型将失败(行为不确定!),因此这不适用于验证不受信任的输入(并且如果输入是受信任的,为什么需要将其输入)经过验证?)
浮点类型的prvalue可以转换为整数类型的prvalue.转换被截断;即,小数部分被丢弃.如果无法在目标类型中表示截断的值,则行为是不确定的.