c++ - 在 C++ 中使用 strtol 获取 long double

标签 c++ arrays strtol long-double

我正在尝试从数组中取出长 double 值。

long double num;  
char * pEnd;  
char line[] = {5,0,2,5,2,2,5,4,5,.,5,6,6};  
num = strtold(line1, &pEnd);  

出于某种原因,我得到的数字四舍五入为 502522545.6 我对 C++ 很陌生,所以我做错了什么吗?需要做什么才能得到 num 中的整数而不是四舍五入?

谢谢你的帮助!!!

抱歉,这是我的第一篇文章 =)

所以整个程序代码如下:

class Number  
{  
private:

    long double num ;
    char line[19], line2[19]; 
    int i, k;
public:

    Number()
    {}

    void getData()
    {
        i = 0;
        char ch= 'a';
        cout << "\nPlease provide me with the number: ";
        while ((ch = _getche()) != '\r')
        {
            line[i] = ch;
            line2[i] = ch;
            i++;
        }
    }
    void printData() const
    {
        cout << endl;
        cout << "Printing like an Array: ";
        for (int j = 0; j < i; j++)
        {
            cout << line[j];
        }
        cout << "\nModified Array is: ";
        for (int j = 0; j < (i-k); j++)
        {
            cout << line2[j];
        }
        cout << "\nTHe long Double is: " << num;

    }
    void getLong()
    {
        char * pEnd;
        k = 1;
        for (int j = 0; j < i; j++)
        {
            if (line2[j+k] == ',')
            {
                k++;
                line2[j] = line2[j + k];
            }
            line2[j] = line2[j + k];
        }
        line2[i -k] = line2[19];
        num = strtold(line2, &pEnd);
    }
};

int main()  
{  
    Number num;  
    char ch = 'a';  
    while (ch != 'n')  
    {  
        num.getData();  
        num.getLong();  
        num.printData();  
        cout << "\nWould you like to enter another number ? (y/n)";  
        cin >> ch;   
    }  
    return 0;  
}

想法是输入的数字采用以下格式($50,555,355.67)或任何其他数字。然后程序会删除除数字和“.”之外的所有符号。 然后我试图从数组中取出 long double num。 如果您运行该程序,您总是会从 num 中得到四舍五入的数字。

最佳答案

C++ 的实现方式非常简单:

#include <sstream>
#include <iostream>
#include <iomanip>

int main() {
  const std::string line = "502522545.566";  
  long double num;  

  std::istringstream s(line);

  s >> num;

  std::cout << std::fixed << std::setprecision(1) << num << std::endl;
}

关于c++ - 在 C++ 中使用 strtol 获取 long double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906616/

相关文章:

arrays - 无法在Powershell中将字符数组写入文件

python - 将键盘表示为 3D 数组

c++ - 在没有循环/条件的情况下将字符串检查为 int 错误

c++ - MFC:混淆 ON_COMMAND 函数?

c++ - 如何为模板类添加运算符<<?

c++ - 实例化类的正确方法

Java ArrayList<Object[]> 到 Object[][]

将十六进制字符串转换为 signed int 会在不同平台上产生不同的值

c - 为什么 strtol() 对于非常大的数字返回 -1?

C++错误: no match for 'operator<<' (operand types are