c++ - 获取数字的小数部分

标签 c++

<分区>

尝试将数字的整数部分和小数部分放入两个变量中。我尝试了什么:

#include <iostream>
int main(){
    float n,m; int k; std::cin >> n;
    k = n;
    m = n - k;

尝试将 float 转换为 int 并收到编译器警告,该数字可能不正确,经过测试,确实不正确,无法获得预期结果。对此进行搜索,除了使用 floor() 之外找不到任何其他解决方法。

我的实际代码:

int main() {
    float n; cin >> n;
    int nfloor = n;
    cout << nfloor << "\n";
    float nfloat = n - nfloor; int nfloatfloor;
    cout << nfloat << "\n";
    do {
        nfloat *= 10;
        nfloatfloor = nfloat;
        cout << nfloat << "\n" << nfloatfloor << "\n";
    } while (nfloat > nfloatfloor);
}

结果:

Input: 12.34
Output :
12
0.34
3.4
3
34
34
340
340
3400
3400
34000
34000
340000
340000
3.4e+06
3400001
3.4e+07
34000016

两个 float 相减会返回一个不正确的值,对此进行了搜索,但答案的级别很高,我无法理解。

我的实际代码:

int main() {
    float n; cin >> n;
    float nfloor = floor(n);
    cout << nfloor << "\n";
    float nfloat = n - nfloor; float nfloatfloor;
    cout << nfloat << "\n";
    do {
        nfloat *= 10;
        nfloatfloor = floor(nfloat);
        cout << nfloat << "\n" << nfloatfloor << "\n";
    } while (nfloat > nfloatfloor);
}

结果:

Input: 12.34
Output:
12
0.34
3.4
3
34
34 //Run should stop here because of the while loop bit it doesn't, funny thing is it gives me different results sometimes, last time it gave me 35 and 34
340
340
3400
3400
34000
34000
340000
340000
3.4e+06
3.4e+06
3.4e+07
3.4e+07

@Slava 看看这句话上面的输出,编译器打印了 34 和 34,重复的答案显示 couts 是 34.0000000000000004 或类似的东西,正如我在上面评论的那样,代码应该已经停止了,我我真正想做的是比较 float 和整数,如果 (float >int) 代码应该继续,如果不是应该停止,那么有什么解决办法吗? @hnefatl 我试过你的答案,编译器挂起:

int main() {
    float n2, whole, fractional, fractional2, whole2; cin >> n2;
    int denominator = 1;
    fractional = modf(n2, &whole);
    do {
        fractional *= 10;
        fractional2 = modf(fractional, &whole2);
        denominator *= 10;
    } while (fractional > fractional2);
    if (denominator > 1)
        denominator /= 10;
    cout << denominator;
}

最佳答案

为什么不使用 std::modf ,专为此目的而设计:

float n = 12.34;
float whole, fractional;

fractional = std::modf(n, &whole);

值的非小数部分在 whole 中,而小数部分在 fractional 中。


如果您随后想获得整个部分的整数值(请记住,您可能会以这种方式丢失数据,因为 float 的范围可能大于int),你可以这样做:

int integralWhole = static_cast<int>(whole);

关于c++ - 获取数字的小数部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837838/

相关文章:

c++ - 当我们不给 C 可执行程序任何参数时如何处理异常

c++ - Output Befor 给出用于寻找回文的字符串输入

c++ - char 数组上的可变参数

c++ - CMake 没有为编译器使用适当的输出命令行参数

c++ - 无法匹配 MessageBox::Show 的参数列表

c++ - 仅 header 库中的静态成员

c++ - 用户空间内存碎片

c++ - C-定义宏的预处理器

c++ - 如何将 boost::iostreams::null_sink 用作 std::ostream

c++ - 将 C++ 从 Linux 移植到 Windows, '__aligned__'