编一个名为turn的函数,入口参数为double a;返回一个字符串,去掉后面的零。

来源:百度知道 编辑:UC知道 时间:2024/06/24 05:37:03
举例:turn(3.141600000)="3.1416"
turn(8.987)="8.987";

//---------------------------------------------------------------------------

#include <stdio.h>
#include <string.h>

char *turn(double a)
{
static char ch[30];
int i;
sprintf(ch,"%f",a);
for (i=strlen(ch)-1; ch[i]=='0'; --i) {
ch[i]=0;
}
return ch;
}

int main(int argc, char* argv[])
{
double b=3.1416;
printf("%f\n%s\n",b,turn(b));
return 0;
}
//---------------------------------------------------------------------------

double turn(double source )
{
char buffer[128];
memset(buffer,0,128);
sprintf(buffer,"%f",source);
char pos = buffer + 127;
while(*pos == 0 || *pos == '0' || *pos == '.')
{
*pos = 0;
pos--;
}
return atof(buffer);
}