简体   繁体   English

C++ 如何将 char* 精确转换为 double?

[英]C++ How to translate char* to double with precision?

I have an assignment ask for a program:我有一个任务要求一个程序:

Input:输入:

  1. receive multiple line of input.接收多行输入。
  2. each line contains 1-10 floating point numbers and separated by 1 or more white-space.每行包含 1-10 个浮点数,并由 1 个或多个空格分隔。

Output: Output:

  1. the answer is the sum of each line ( it should round up to 4 decimal places) and it can be stored in variable with signed double type.答案是每行的总和(它应该四舍五入到小数点后 4 位),它可以存储在带符号双精度类型的变量中。
  2. each answer should be printed in a single line.每个答案都应打印在一行中。
  3. there is a blank line between consecutive answer.连续答案之间有一个空行。

The sample input:样本输入:

1 3 5 7 9
2 4.6 5.01

and the sample output:和样品 output:

25.0000

11.6100

I have tried many time and my program still cannot produce the correct output (I submit it to the online judgment system, which is offered by my school, and get "wrong answer" message.).我尝试了很多次,我的程序仍然无法产生正确的output(我将它提交到我学校提供的在线判断系统,并得到“错误答案”的消息。)。

Here is my code:这是我的代码:

#include <iostream>
#include <iomanip>
#include <cstring>
#include <math.h>

using namespace std;

const int N = 100;
char line[N];

int main () {
    while( fgets( line, N, stdin ) ) {
        char* word = strtok( line, " " );
        double result = 0.0000;

        while( word != NULL ) {
           if( isdigit(word[0]) || word[0] == '-' ) {
                result += atof(word);
           }
           word = strtok( NULL, " " );
        }

        int temp;
        if(result < 0) {
            temp = floor(result * 10000.0);
        } else {
            temp = ceil(result * 10000.0);
        }

        result = (double) temp/10000.0;

        cout << fixed << setprecision(4) << result << endl << endl;
    }

    return 0;
}

Here is my test case:这是我的测试用例:

1 3 5 7 9
2 4.6 5.01
-1 -3 -5 -7 -9
-2 -4.6 -5.01
-1.555587 -1.555587 -1.555587 -1.555587 -1.555587 -1.555587 -1.555587 -1.555587 -1.555587 -1.555587

and the corresponding result:以及相应的结果:

25.0000

11.6100

-25.0000

-11.6100

-15.5559

What is the problem in my code?我的代码有什么问题? I guess it may be related to the conversion from char* to double, this process may lead some loss and lead to the "wrong answer".我猜这可能与从 char* 到 double 的转换有关,这个过程可能会导致一些损失并导致“错误答案”。 Isn't it?不是吗? If no, please tell me what wrong with it.如果没有,请告诉我它有什么问题。

The problem is with how you handle rounding.问题在于如何处理舍入。 The assignment says it should round up to 4 decimal places but your code is rounding away from zero ( ceil for positive, floor for negative).作业说它应该四舍五入到小数点后 4 位,但您的代码从零四舍五入( ceil表示正数, floor表示负数)。

You should use ceil for all numbers.您应该对所有数字使用ceil Get rid of int temp;摆脱int temp; , all uses of temp , and replace the assignment to result with: temp的所有用途,并将result的赋值替换为:

result = ceil(result * 10000.0) / 10000.0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM