0

我试图从数组中取出长双精度数。

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 中得到四舍五入的数字。

4

3 回答 3

3

这样做的 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;
}
于 2015-03-06T20:10:39.510 回答
2

使用现代 C++,您可以简单地执行以下操作:

auto line = "502522545.566"s;

auto num = std::stold(line);

Live example

于 2015-03-06T20:26:59.727 回答
0

可能有更多的 C++ 方式,但 sscanf 会起作用:

const char *str = "3.1459";
long double f;
sscanf(str, "%Lf", &f);
于 2015-03-06T20:10:03.210 回答