C ++ Float Var四舍五入

时间:2011-09-15 01:22:15

标签: c++

  

可能重复:
  Equation not working correctly in C++
  Help with POW function in C++

在此代码中:

//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;
}

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

1 个答案:

答案 0 :(得分:5)

我们假设我对cout的作用一无所知。因为我对cout一无所知,所以我对“c ++ cout”进行搜索引擎查询。我点击第一页上的其中一个链接such as this MSDN doucmentation。根据该页面,我发现coutostream,输出到标准输出。让我们查看ostreamso conveniently provided in the MSDN documentation。在ostream页面上,有a link called "iostream Programming"。这看起来很有希望,所以让我们点击它。

“iostream Programming”页面上有a link called "Output Streams"。再次,这看起来很有希望。毕竟,我们正在向屏幕输出一些内容,所以让我们来看看。在该页面上,有a link called "Using Insertion Operators and Controlling Format"。听起来我们已经接近了。

瞧,我偶然发现了一个显示“如何控制格式”的页面。该页面上有一个名为“Precision”的部分,描述了函数setprecision() and setiosflags() complete with code examples。根据文档,也许它可能会解决您的问题。

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