69,371
社区成员
发帖
与我相关
我的任务
分享
/* Exercise 5.1 Get the reciprocals */
#include <stdio.h>
int main(void)
{
double values[5] = {0.0}; /* Store five doubles */
double reciprocals[5] = {0.0}; /* Store the reciprocals of the five values */
double sum = 0.0; /* Store the sum of reciprocals */
printf("Enter five doubles you want: \n");
for(int i = 0 ; i < 5 ; i++)
{
scanf("%lf" , &values[i]); //取值的时候用 %lf 就行.
}
/* Get the reciprocals */
for(int i = 0 ; i < 5 ; i++)
{
reciprocals[i] = 1.0 / values[i];
printf("values[%d] is: %.3f\n" , i , values[i]); // 改成 %.3f 就可以了.
}
/* Display the sum of the reciprocals */
for(int i = 0 ; i < 5 ; i++)
{
sum += reciprocals[i];
}
printf("The sum of reciprocals is: %.3f\n" , sum); // 同上
return 0;
}
/*
**********************************************************************
我用CodeBlocks, GNU-GCC 编译的. 我也不清楚为啥获取值的时候用 %lf,
打印的时候就用 %f. 不然也会出现你这个问题, 输出是 0. 求高手
讲解. 另外, 没改正之前, VS2008运行你的程序没有问题. 结果正常.
**********************************************************************
*/
#include <stdio.h>
int main(void)
{
double values[5] = {0.0}; /* Store five doubles */
double reciprocals[5] = {0.0}; /* Store the reciprocals of the five values */
double sum = 0.0; /* Store the sum of reciprocals */
int i; //把后边用到的i提前声明在了这里
printf("Enter five doubles you want: \n");
for(i = 0 ; i < 5 ; i++)
{
scanf("%lf" , &values[i]);
}
/* Get the reciprocals */
for(i = 0 ; i < 5 ; i++)
{
reciprocals[i] = 1.0 / values[i];
printf("values[%d] is: %.3lf\n" , i , values[i]);
}
/* Display the sum of the reciprocals */
for(i = 0 ; i < 5 ; i++)
{
sum += reciprocals[i];
}
printf("The sum of reciprocals is: %.3lf\n" , sum);
return 0;
}
wangxiao@Main-WangXiao ~$ ./a.out
Enter five doubles you want:
1.2
2.3
3.4
4.5
5.6
values[0] is: 1.200
values[1] is: 2.300
values[2] is: 3.400
values[3] is: 4.500
values[4] is: 5.600
The sum of reciprocals is: 1.963
#include <stdio.h>
int main(void)
{
double values[5] = {0.0}; /* Store five doubles */
double reciprocals[5] = {0.0}; /* Store the reciprocals of the five values */
double sum = 0.0; /* Store the sum of reciprocals */
int i = 0;
printf("Enter five doubles you want: \n");
for(i = 0 ; i < 5 ; i++)
{
scanf("%lf" , &values[i]);
}
/* Get the reciprocals */
for( i = 0 ; i < 5 ; i++)
{
reciprocals[i] = 1.0 / values[i];
printf("values[%d] is: %.3lf\n" , i , values[i]);
}
/* Display the sum of the reciprocals */
for( i = 0 ; i < 5 ; i++)
{
sum += reciprocals[i];
}
printf("The sum of reciprocals is: %.3lf\n" , sum);
return 0;
}
//VC6.0运行正常的