function (programming C++)?

2009-08-02 5:30 pm
Write a program with function that receives a positive floating-point number and rounds it to two decimal places. For example, if 123.456789 is passed to the function, 123.460000 would be returned by the function.

anyone can give me some hints to do this question. I was totally blank with it.. =(

thanks a lot!

回答 (4)

2009-08-02 11:20 pm
✔ 最佳答案
"Paul" I tried to use function round(double) <math.h> but I still get "undeclared identifier" error!!! do you know why???

I wrote this function:
float round(const float &number, unsigned int precision=(unsigned int)3)
{
if(precision>6)
precision = 3; // set Default

if(number>0.0)
{
// holds the integer value of 'number'
int integer = (int)floor(number);
// holds the decimal value of 'number'
int decimal = (number-integer) * pow(10,(double)precision);
// truncate decimal value with respect to 'precision'
float truncated = ((float)decimal) / (float)pow(10,(double)precision);

// holds the last digit of the decimal value
int ldigit = decimal % 10;

if(ldigit>=5 && precision==1)
{
integer += 1;
return static_cast<float>(integer);
}
else if(ldigit>=5)
decimal += 10 - ldigit; // round
else
decimal /= 10; // truncate

truncated = ((float)decimal) / (float)pow(10,(double)precision); // update

return static_cast<float>(integer) + truncated;
}
return number;
}

Another function to round double number and more precise:
http://stackoverflow.com/questions/554204/where-is-round-in-c
#include <iostream>
#include <sstream>
double round(double val, int precision)
{
std::stringstream s;
s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
s >> val;
return val;
}
2009-08-03 3:06 am
Ignore the suggestions about converting to/from int. Just multiply by 100.0, call round(), then divide by 100.0.
參考: % man round
2009-08-03 1:31 am
Like what monchanger said.

multiply your number by 100, then convert your number to an int.
Now convert it back to a double/float and divide again by 100.
2009-08-03 1:11 am
Removing decimal places can be done by converting to an integer.
But... if you do that to the original number, you'll lose the two digits you need.
But... if you multiply by 100, those digits will be saved.

Good luck!


收錄日期: 2021-05-01 12:42:43
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090802093022AAdAyze

檢視 Wayback Machine 備份