帮忙写一个基础函数
要求写一个函数, amt是传入值的指针,n是保留的小数位数。类似四舍五入函数,但进位有所不同
要求用纯C写
double roundm(amt,n)
double *amt;
int n;
{
////////代码
////////代码
................
...............
}
//调用
double x,y,z;
x=6.0068003
y=6.0068008
z=6.0068000
roundm(&x,6) = 6.006801
roundm(&y,6) = 6.006801
roundm(&z,6) = 6.006800
求中间代码
[解决办法]
//Round(1.234,2) = 1.23//Round(1.234,0) = 1.0//Round(123.4,-1) = 120.0double Round(double dVal, short iPlaces) { double dRetval; double dMod = 0.0000001; if (dVal<0.0) dMod=-0.0000001; dRetval=dVal; dRetval+=(5.0/pow(10.0,iPlaces+1.0)); dRetval*=pow(10.0,iPlaces); dRetval=floor(dRetval+dMod); dRetval/=pow(10.0,iPlaces); return(dRetval);}double round(double dVal, short iPlaces) //iPlaces>=0{ unsigned char s[20]; double dRetval; sprintf(s,"%.*lf",iPlaces,dVal); sscanf(s,"%lf",&dRetval); return (dRetval);}
[解决办法]
#include <stdio.h>#include <math.h>#include <stdlib.h>double roundm(double *amt, int n){// (int)(*amt * pow(10.0, n + 1)) % 10 == 0 ? *amt = (int)(*amt * pow(10.0, n)) / pow(10.0, n) : *amt = (((int )*amt * pow(10.0, n)) + 1) / pow(10.0, n); if ((int)(*amt * pow(10.0, n + 1)) % 10 == 0) { *amt = (int)(*amt * pow(10.0, n)) / pow(10.0, n); } else { *amt = (((int )(*amt * pow(10.0, n))) + 1) / pow(10.0, n);//少加了个括号 } return *amt;}int main(){ double amt = 6.0068003; roundm(&amt, 6); printf("%f\n", amt); return 0;}~
[解决办法]
照4楼的规则,将我的程序改了一下。
先给出运行结果:
roundm(6.006800300000,6)=6.006801000000
roundm(6.006800800000,6)=6.006801000000
roundm(6.006800000000,6)=6.006800000000
再给出源代码
#include <stdlib.h>#include <stdio.h>#include <math.h>double roundm(double f,int n){ double t1,t2; t1= f* pow(10.0,1.0*n); t2= t1-floor(t1); t1=floor(t1); if (t2>=0.1) t1+=1.0; t1= t1 / pow(10.0, n); return t1;}int main(){ double x; x=6.0068003; printf("roundm(%.12f,%d)=%.12f\n",x,6,roundm(x,6)); x=6.0068008; printf("roundm(%.12f,%d)=%.12f\n",x,6,roundm(x,6)); x=6.0068000; printf("roundm(%.12f,%d)=%.12f\n",x,6,roundm(x,6));}
[解决办法]
// roundm.cpp
#include <math.h>
#include <stdio.h>
#include <conio.h>
/*
#include <iostream>
#include <iomanip>
*/
double roundm(double* amt,int n)
{
double ABC = pow(10.0,n+1);
int t = (int)(*amt*ABC);
int x = t%10;
if(x)
return (t-x+10)/ABC;
else
return t/ABC;
}
int main()
{
extern double roundm(double *amt,int n);
double x,y,z;
x=6.0068003;
y=6.0068008;
z=6.0068000;
printf("%f\n",roundm(&x,6));
/*
double num;
int m;
std::cin >> m >> num;
std::cout << std::setprecision(16)<< roundm(&num,m) << std::endl;
*/
getch();
return 0;
}
/*
老实说,C语言中的输入输出流是最让我难受的一部分。
*/