【发布时间】:2015-06-14 03:16:19
【问题描述】:
这是UVa在线法官问题的链接。
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=29&page=show_problem&problem=1078
我的 C 代码是
#include <stdio.h>
double avg(double * arr,int students)
{
int i;
double average=0;
for(i=0;i<students;i++){
average=average+(*(arr+i));
}
average=average/students;
int temp=average*100;
average=temp/100.0;
return average;
}
double mon(double * arr,int students,double average)
{
int i;
double count=0;
for(i=0;i<students;i++){
if(*(arr+i)<average){
double temp=average-*(arr+i);
int a=temp*100;
temp=a/100.0;
count=count+temp;
}
}
return count;
}
int main(void)
{
// your code goes here
int students;
scanf("%d",&students);
while(students!=0){
double arr[students];
int i;
for(i=0;i<students;i++){
scanf("%lf",&arr[i]);
}
double average=avg(arr,students);
//printf("%lf\n",average);
double money=mon(arr,students,average);
printf("$%.2lf\n",money);
scanf("%d",&students);
}
return 0;
}
输入和输出之一是
输入
3
0.01
0.03
0.03
0
输出
$0.01
我的输出是
0.00 美元。
但是,如果我取消注释 printf("%lf",average);
输出如下
0.02 //这是平均值
0.01 美元
我在 ideone.com 上运行代码
请解释为什么会这样。
【问题讨论】:
-
写
(*(arr+i))而不是arr[i]不会让你看起来更酷:) -
这可能是某种舍入问题 - 也许您的计算机正在将输出计算为
0.00999999或其他东西。如果是这样,你可能想用整数美分来做所有的数学运算(假设问题允许你这样做)。 -
...但是
printf实际上确实对输出进行了舍入,所以不可能这样。我也得到$0.01作为输出,奇怪的是...... -
@AdityaSharma:
$0.01在我的机器上,$0.00on IDEOne。我还没有在这里看到任何 UB 的东西,但有些东西显然是可疑的...... -
请注意,顺便说一句,可变长度数组是 C99 的一项功能,尽管 GCC 在 C90 模式下也默认识别它们。您的代码可以接受地使用它们,但它确实会在一个有点靠近边缘的区域使用它更新 VLA 范围内的长度表达式的值的方式,从而在每次迭代时为 VLA 提供不同的长度。这些不是编程错误,但它们是可能存在编译器错误的地方。
标签: c