gpt4 book ai didi

C++浮点题

转载 作者:行者123 更新时间:2023-11-30 05:48:56 25 4
gpt4 key购买 nike

我很难理解 float 和 double 的概念。

#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 的 float (如美元),但在我编译时 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;

关于C++浮点题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com