获得数字的十进制部分

Get decimal part of a number

本文关键字:十进制部 数字      更新时间:2023-10-16

试图将一个数字的整数和十进制部分分为两个变量。我尝试的是:

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

试图将浮点数转换为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

减去两个浮点数返回一个不正确的值,对此进行了搜索,但答案处于我无法理解的高级别。

我的实际代码:

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或类似的东西,正如我在上面评论的那样,代码应该停止,我是我的。'我真的试图做的是比较一个浮点数和int编号,如果(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);

这应该可以解决问题。

int main(){
    float n; std::cin >> n;
    float whole = floor(n);
    float decimal = n - whole;
    std::cout << whole << "n";
    std::cout << decimal << "n";
    std::cin.get();
    return 0;
}