[英]C++ How to translate char* to double with precision?
I have an assignment ask for a program:我有一个任务要求一个程序:
Input:输入:
Output: Output:
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.