给大家分享c语言处理四舍五入的三种解决方法!!!
我最喜欢第一种round1()!!!
因为我觉得其他两种不通用!!!
//四舍五入 round
//头文件
#include<stdio.h>
#include<stdlib.h> //提供srand() rand()
#include<math.h> //提供round() pow()
#include<time.h> //提供time(NULL)
#include<windows.h>//提供Sleep()
//函数声明
double Calculate(int ,char ,int,int);
void round1(int); //除法:保留给定精度的结果
void round2(); //除法:四舍五入保留整数位
void round3(); //除法:c语言中round函数的用法 round函数只有一个参数 有两个参数的不是c语言
//主函数
int main()
{
int precision;
printf("输入你想要保留的精度:\n");
scanf("%d",&precision);
round1(precision);
round2();
Sleep(1000); //为了避免round2()和round3()产生的随机数一样
round3();
return 0;
//以下是测试程序(为了弄清楚round2()和round3()的srand(time(NULL))为什么是一样的)
// round2();
//
// round3();
// -26/99=0
//
// -26/99=-0
//
// Process returned 0 (0x0) execution time : 0.358 s
// Press any key to continue.
// srand(time(NULL))的办法产生随机数,但是time(NULL)产生的时间是以秒为单位,如果程序循环在一秒钟之内执行完,那么time(NULL)每次返回的时间也就是一样的,所以造成srand(time(NULL))每次取的种子也都一样。
// 大家可以看到这个测试程序的时间是0.358s!!!
// 所以这个程序中srand(time(NULL))产生的随机数是一样的。
}
//我认为的最好的四舍五入计算方法
double Calculate(int a,char ch,int b,int precision)
{
double c=(double)a/b; //(double)a/b 是将a转换成double (double)(a/b) 是将a/b整体转换成double
double OutputAnwser;
if(c>=(double)0) //这里需要对c进行判断 正负数的处理是不一样的
{
OutputAnwser=((c*pow((double)10,precision))+0.5)/pow((double)10,precision);
}
else
{
OutputAnwser=((c*pow((double)10,precision))-0.5)/pow((double)10,precision);
}
return OutputAnwser; //这里的OutputAnwser还不是最终的精确度的结果 后续仍然需要处理
}
void round1(int precision)
{
int a,b;
char ch='/';
double c;
double UserAnwser;
srand(time(NULL));
a=rand()%100-50; //a的取值范围是[-50,50) a是被除数 可以为0
b=rand()%100+1; //b的取值范围是[1,101) b是除数 不可以为0
c=Calculate(a,ch,b,precision);
printf("\n%d%c%d=\n",a,ch,b);
scanf("%lf",&UserAnwser);
if(UserAnwser==c)
{
printf("\nWonderful!\n");
}
else
{
printf("\nRightAnwser is %.*lf!\n",precision,c); //printf格式化输出 %.*lf *表示读取一个int型数据作为精度 是对c的进一步处理
}
}
void round2()
{
int a,b;
int c;
srand(time(NULL));
a=rand()%100-50;
b=rand()%100+1;
if(a>=0)
{
c=(a+b/2)/b;
}
else
{
c=(a-b/2)/ b;
}
printf("\n%d/%d=%d\n",a,b,c);
}
void round3()
{
int a,b;
double c;
srand(time(NULL));
a=rand()%100-50;
b=rand()%100+1;
c=round((double)a/b);
printf("\n%d/%d=%.0lf\n",a,b,c);
}
测试结果:
输入你想要保留的精度:
2
-14/34=
1
RightAnwser is -0.42!
-4/11=0
-1/92=-0
Process returned 0 (0x0) execution time : 8.963 s
Press any key to continue.
这里round2()和round3()产生的结果分别是0和-0的原因是:我round2()中定义的c是int类型,而我round3()中定义的c是double类型,所以在经过控制输出后才产生这样的结果。