(C ++)如何舍入小数,例如1.05000?

时间:2019-06-28 14:57:06

标签: decimal rounding

我有一个问题,在我的算法中,我应该将结果四舍五入到小数点后五位,即使在最后一个数字之后也要包含零。

在我的算法中不起作用的唯一测试用例是:

  

输入

     

牛奶1    4    面包    肉    牛奶    aaaaa

     

输出

     

1.05000 // //我的输出显示1.5

例如;我的 1.05 结果应显示为 1.05000 或1.2显示为1.20000。现在,其余算法工作正常,因此唯一的问题是四舍五入部分:

 #include <iostream>
 #include <string.h>

 using namespace std;

 int main()
 {

 char name[50];
 cin >> name;
 double price = 0;
 cin >> price;
 int N;
 cin >> N;
 char check_name[50];
 double result = 0;
 bool found = false;
 double result_circle = 0;
 int finally_found = 0

 for (int k = 0; k < N; k++) {
    cin >> check_name;
    for (int i = 0; i < strlen(name); i++) {
        if (name[i] == check_name[i]) {
            found = true;
        } else {
            found = false;
            break;
        }
    }
    if (found) {
        finally_found++;
        break;
    }
 }

 if (finally_found > 0) {
    result = price + (price * 0.05);
 } else {
    result = price + (price * 0.18);
 }

 // here is where the problem starts

 result_circle = result * 1000000; //temporarily expanding the number to the 6th decimal place
 if ((int)result_circle % 10 > 4) { // checking if the 6th decimal place is bigger than 4
    result_circle += 10; // increasing the 5th decimal place
 }

 result_circle = (int)result_circle / 10; // removing the 6th decimal place which we were checking

 cout << (int)result_circle / 100000 << '.' << (int)result_circle % 100000; // here is the main problem, where 105000 % 100000 is seen as 5000 not 05000

    return 0;
 }

我认为这里的主要问题是“ 105000%100000 = 5000”,因为不幸的是,小数点后的0被忽略了。

如果有人能显示出解决此问题的最简单方法,那就太好了。

1 个答案:

答案 0 :(得分:0)

#include <iomanip> 
 .
 .
 .
cout << fixed << setprecision(5) << result;

这是对我有用的代码,由_Bob回答。

完整代码:

#include <iostream>
#include <string.h>
#include <iomanip>

using namespace std;

int main()
{

    char name[50];
    cin >> name;
    double price = 0;
    cin >> price;
    int N;
    cin >> N;
    char check_name[50];
    double result = 0;
    bool found = false;
    double result_circle = 0;
    int finally_found = 0;

    for (int k = 0; k < N; k++) {
        cin >> check_name;
        for (int i = 0; i < strlen(name); i++) {
            if (name[i] == check_name[i]) {
                found = true;
            } else {
                found = false;
                break;
            }
        }
        if (found) {
        finally_found++;
    }
}

if (finally_found > 0) {
    result = price + (price * 0.05);
} else {
    result = price + (price * 0.18);
}

cout << fixed << setprecision(5) << result;

return 0;
}