【问题标题】:C++ String to Number Custom function problemC++ String to Number 自定义函数问题
【发布时间】:2021-06-15 17:30:34
【问题描述】:

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

附加信息:

  • 编译器:mingw
  • 操作系统:win10

这是代码(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:\--路径-->test.exe
-912.302

后来发现的:

如果在主函数中,我们传递“-912.3016”
cout 然后输出结果是:

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

但是如果我们通过“-912.3015”
cout 然后是o/p:

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

我应该使用 double 而不是 long double 还是有其他问题?

【问题讨论】:

  • 通过== 比较双打是有问题的,但是为了进行正确的测试,您可以编写一个将数字转换回字符串的函数,以查看您是否获得了原始字符串。即使通过cout 将您当前的问题放在一边测试也不是那么可靠
  • btw pow 不是用整数调用的。无论如何,在循环索引为count 的循环中调用pow(x,count) 是浪费cpu 周期。在每个循环中累积*0.1 要简单得多
  • 试试cout &lt;&lt; -912.301956;,它也会打印-912.302。

标签: c++ string numbers


【解决方案1】:

std::cout 的默认 precision 是 std::ios_base::init 设置的 6。所以

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    相关资源
    最近更新 更多