C++ 返回设定小数点后位数的值

来源:百度知道 编辑:UC知道 时间:2024/06/15 21:54:31
输入一个浮点型,要求对该数格式化,即确定其精度,并把格式话后的值返回,知道怎么输出,重点在返回。
描述一下:
double a,b;
cin>>a;
b=function(a);
怎样写function函数呢?就保留小数点后一位

不是很懂你的你的意思, 看看下面的程序是不是你要的, function(a) 的返回值为 a保留小数点后1位。

#include <stdio.h>

double function(double a)
{
char buffer[128];
double ret;
sprintf(buffer, "%.1lf", a);
sscanf(buffer, "%lf", &ret);
return ret;
}

int main()
{
double a, b;
printf("Input a double number!\n");
scanf("%lf", &a);

printf("%lf\n", function(a));
return 0;
}

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

double func(double b)
{
double tmp =0.0;
char buf[50],*p = NULL;
int nLen = 0;

memset(buf,0,50);

sprintf(buf,"%lf",b);
p = strstr(buf,".");
if( (p != NULL)// exist '.'
&& (p+1)!=NULL //exist digit
&& (p+2)!=NULL)//exist next digit
{
memset(p+2