C ++浮点问题

时间:2015-01-17 15:32:51

标签: c++ floating-point

我在使用花车时遇到困难。双打概念。

#include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;

int main() {

    const float classA = 15.00f;
    const float classB = 12.00f;
    const float classC = 9.00f;
    int soldA,
    soldB,
    soldC;
    float total = 1.00f;

    std::cout << "How many Class A tickets where sold? : ";
    std::cin >> soldA;
    std::cout << "How many class B tickets were sold? : ";
    std::cin >> soldB;
    std::cout << "How many Class C tickets were sold? : ";
    std::cin >> soldB;

    printf("%f\n", total = (classA * soldA) + (classB * soldB) + (classC * soldC));

    std::cout <<"The total amount collected : $" << total << endl;
}

在最后一行,我想打印总数为精度为2的浮点数(如美元),但是在编译时printf工作正常,但它在最后一行失去了精度。

我该如何解决这个问题?或者显示精度?

2 个答案:

答案 0 :(得分:1)

您需要在std::cout上设置精确度,如下所示:

std::cout.precision(2);
std::cout <<"The total amount collected : $" << total << endl;

或者您也可以这样设置:

std::cout <<"The total amount collected : $" << std::setprecision(2) << total << endl;

答案 1 :(得分:0)

#include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;

int main() {

    const float classA = 15.00f;
    const float classB = 12.00f;
    const float classC = 9.00f;
    int soldA,soldB,soldC;
    float total = 1.00f;

    std::cout << "How many Class A tickets where sold? : ";
    std::cin >> soldA;
    std::cout << "How many class B tickets were sold? : ";
    std::cin >> soldB;
    std::cout << "How many Class C tickets were sold? : ";
    std::cin >> soldC;

    printf("%f\n", total = (classA * soldA) + (classB * soldB) + (classC * soldC));

    std::cout.precision(2);     // set precision
    std::cout << std::fixed;    // use the precision for numbers like 66.000000
    std::cout <<"The total amount collected : $" << total << endl;
}

享受:)