请编写一个函数float fun(double h),该函数的功能是:使变量h中的值保留两位小数,并对第三位进行四舍五入(规定h中的值为正值)。列如h为 1234.567则函数返回1234.570000;#include <stdio.h>#include <conio.h>#include <stdlib.h>float fun (float h ){float i;int j;h*=1000;j=((int)h)%10;if(j>=5){h=h+10-j;}else{h=h-j;}h/=1000;i=(float)h;return h;}void main(){ FILE *wf; float a; system("CLS"); printf("Enter a: "); scanf ("%f",&a); printf("The original data is : "); printf("%f\n\n", a); printf("The result : %f\n", fun(a));/******************************/ wf=fopen("out.dat","w"); fprintf(wf,"%f",fun(8.32533)); fclose(wf);/*****************************/}非常感谢!!红线标出了我写的东西!
两行代码能解决的问题,你搞得太复杂了。
float fun(double h) //按题目要求,h的类型为double型{
int j=(int)(h*100+0.5);
return((float)j/100);
}
而且,既然是保留两位小数,最后输出应该是
printf("The result: %.2lf\n",fun(a));追问先不管他保留几位小数,我写的这个是我看到这个题的时候最初的想法,我就想知道哪里错了,避免我以后把这种错误带到其他题目里面!