C++ Float Var四舍五入

Sam*_*nna -3 c++

可能重复:
方程式在C++ 帮助中无法正常工作C++中的
POW函数

在此代码中:

//Samuel LaManna
//Program 1 (intrest rate)
/*Variables:
Principal=P
Interest Rate=R
Times Compounded=T
Savings=S
Interest=I */

#include <iostream>     //Input/output
#include <cmath>        //Math Functions

using namespace std;

int main ()
{
  float P, R, T, S, I;                                                                      //Declaring Variables
  cout<<endl;
  cout<<"Interest Earned Calculator";                                                       //Prints program title
  cout<<endl;
  cout<<endl;
  cout<<"Please enter the Principal Value: ";
  cin >> P;
  cout<<endl;
  cout<<endl;
  cout<<"Please enter the Interest Rate (in decimal form): ";
  cin >> R;
  cout<<endl;
  cout<<endl;
  cout<<"Please enter the Number of times the interest is compounded in a year: ";
  cin >> T;
  cout<<endl;
  cout<<endl;
  S=pow(1+R/T,T)*P;    //Equation to find Savings
  I=S-P;               //Equation to find interest in $
  cout<<"Interest Rate: " << R*100 <<"%" ;
  cout<<endl;
  cout<<endl;
  cout<<"Times Compounded: " << T;
  cout<<endl;
  cout<<endl;
  cout<<"Principal: $" << P;
  cout<<endl;
  cout<<endl;
  cout<<"Interest: $" << I;
  cout<<endl;
  cout<<endl;
  cout<<"Ammount in Savings: $" << S;
  cout<<endl;
  cout<<endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使最终输出数字舍入到2位小数,即使它们是0?

In *_*ico 5

让我们假设我什么都不知道cout.因为我一无所知cout,所以我为"c ++ cout"做搜索引擎查询.我单击第一页上的其中一个链接,例如此MSDN doucmentation.根据该页面,我发现这cout是一个ostream输出到标准输出.所以让我们查一下ostream,在MSDN文档中提供的方便.在ostream页面上,有一个名为"iostream Programming"的链接.这看起来很有希望,所以让我们点击它.

"iostream Programming"页面上有一个名为"Output Streams"的链接.再次,这看起来很有希望.毕竟,我们正在向屏幕输出一些内容,所以让我们来看看.在该页面上,有一个名为"使用插入操作符和控制格式"的链接.听起来我们越来越近了.

瞧,我偶然发现了一个显示"如何控制格式"的页面.该页面上有一个名为"Precision"的部分,它描述了函数setprecision()setiosflags()完成了代码示例.根据文档,也许它可能会解决您的问题.

我采取的上述过程通常被互联网成员俗称为"RTFM".这是一种非常有用的技术,可以自己获取信息,并可以利用您的优势来领先于同行.