首页 > 解决方案 > C++ String to Number 自定义函数问题

问题描述

我正在尝试在 C++ 中将字符串转换为数字(长双精度)。当小数点后的位数大于 3 时会出现问题。它会自动将小数点后四舍五入到最接近的第三位。

附加信息:

这是代码(test.cpp):

#include<iostream>
#include <string>
#include <math.h>

using namespace std;

double long c2n(string n) {
    double long num=0;
    bool isdec = false, is_ve=false;
    // is_ve checks if number is negative
    // isdec checks if the decimal point is reached and numbers can be added after decimal
    char c;
    // to store the the character which needs to be checked
    short i = 0, count=1;
    if (n.at(0)=='-')
    {
        i=1;
        is_ve=true;
    }
    for (; i < n.length(); ++i)
    {
        c=n.at(i);
        if (c=='.'){
            isdec=true;
            continue;
        }

        if (!isdec)
            num=num*10+(c-'0');
        else{
            num = num + (c-'0')/pow(10,count);
            count++;
        }
    }
    if (is_ve)
    {
        return -num;
    }
    return num;
}

int main(int argc, char const *argv[])
{
    cout << c2n("-912.301956") << endl;
    return 0;
}

这是输出:

D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.302

后来我发现:

如果在主函数中,我们通过 "-912.3016"
cout<< c2n("-912.3016") <<endl;
然后输出是:

D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.302

但是如果我们通过 "-912.3015"
cout << c2n("-912.3015") <<endl;
然后是o / p:

D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.301

我应该采取 double 而不是 long double 还是有其他问题?

标签: c++stringnumbers

解决方案


默认precision值为std::cout6,由 设置std::ios_base::init。所以

auto val = 1234.56789;
std::cout<<val<<'\n`;

产生 1234.57 即 6 位数字(并相应地四舍五入)。从标题中相应地设置precision使用,您应该能够看到正确的值。setprecisioniomanip

std::cout << std::setprecision(12) << c2n("-912.301956") << std::endl;

推荐阅读