C++浮点题

C++ float questions

我很难理解花车和双打的概念。

#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 工作正常,但它在最后一行失去了精度。

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

您需要像这样设置 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;
#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;
}

尽情享受吧:)