gpt4 book ai didi

c++ - 数学计算和 setprecision() 函数有问题

转载 作者:行者123 更新时间:2023-11-28 04:09:50 25 4
gpt4 key购买 nike

我似乎遇到了 C++ 编码问题。它涉及数学运算,我似乎让我的所有输出都正确,除了最后一个。除此之外,我的答案的小数点格式似乎不正确。答案应该包含两位小数,但我的四个小数点答案中只有两个似乎有两位小数。当我尝试使用 precision() 函数时,答案变成了我不想要的科学记数法。

这里是问答:enter image description here

这是我的代码:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
float principal;
float interest_rate;
float times_compounded;

cout << "Hello, please enter a value for your principal: ";
cin >> principal;
cout << principal << endl;
cout << "Please enter a value for your interest rate: ";
cin >> interest_rate;
cout << interest_rate << "%" << endl;
cout << "Please enter the number of times the interest is compounded during the year: ";
cin >> times_compounded;
cout << times_compounded << endl << endl;

float interest = interest_rate * 10.197647;
float amount = principal * pow((1 + (interest_rate/times_compounded)), times_compounded);

cout << "Interest Rate: " << setw(19) << interest_rate << "%" << endl;
cout << "Times Compounded: " << setw(17) << times_compounded << endl;
cout << "Principal: " << setw(17) << "$ " << setw(7) << principal << endl;
cout << "Interest: " << setw(20) << "$ " << interest << endl;
cout << "Amount in Savings: " << setw(9) << "$ " << amount;

return 0;
}

这是我的三个输入:1000, 4.25, 12

如有任何反馈,我们将不胜感激,感谢您抽出宝贵时间。

最佳答案

首先,最后一个值是错误的,因为您在公式中将利率用作正常数字,尽管它实际上是一个百分比。所以你需要将它除以 100:

float amount = principal * pow((1 + ((interest_rate / 100) /times_compounded)), times_compounded);

现在对于精度,您可以结合使用 std::fixedstd::setprecision 来设置使用 std 时的默认浮点打印精度::cout。我们可以使用宏使其更具可读性,例如:

#define FIXED_FLOAT(x, p) std::fixed<<std::setprecision(p)<<(x)

因此,完整的输出部分如下所示:

cout << "Interest Rate: " << setw(19) << FIXED_FLOAT(interest_rate, 2) << "%" << endl;
cout << "Times Compounded: " << setw(17) << FIXED_FLOAT(times_compounded, 0) << endl;
cout << "Principal: " << setw(17) << "$ " << setw(7) << FIXED_FLOAT(principal, 2) << endl;
cout << "Interest: " << setw(20) << "$ " << FIXED_FLOAT(interest, 2) << endl;
cout << "Amount in Savings: " << setw(9) << "$ " << FIXED_FLOAT(amount, 2);

此外,interest = interest_rate * 10.197647 似乎有问题。利息应该只是减去本金的金额。

关于c++ - 数学计算和 setprecision() 函数有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045073/

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