dimanche 3 mai 2020

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.

Output:

  1. the answer should round up to 4 decimal places and it can be stored in variable with signed double type.
  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:

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.).

Here is my code:

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

using namespace std;

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

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

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

        printf("%.4lf\n\n", result);
    }

    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". Isn't it? If no, please tell me what wrong with it.

Aucun commentaire:

Enregistrer un commentaire