测试数字是否具有不带任何库的十进制值 [英] Testing if a number has a decimal value without any library

查看:66
本文介绍了测试数字是否具有不带任何库的十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试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 or ceil or trunc, e.g. test whether x == std::floor(x).

一种不正确的方法:

  • 对于超出目标类型范围的数字,强制转换为整数类型将失败(行为不确定!),因此这不适用于验证不受信任的输入(并且如果输入是受信任的,为什么需要将其输入)经过验证?)

浮点类型的prvalue可以转换为整数类型的prvalue.转换被截断;即,小数部分被丢弃.如果无法在目标类型中表示截断的值,则行为是不确定的.

这篇关于测试数字是否具有不带任何库的十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆