下午考试遇到一道题,说编写一个程序,输入某地12个月的降水量,计算每个月降水量占全年降水量的比例,
并且要求输出样式如图:

其中,比例值要四舍五入,本来很早就能考完了,但是四舍五入的方法我想了好久才弄出来,悲剧啦.
代码如 
#include<iostream>
using namespace std;
#include<iomanip>
int fun(double s);
int main()
{
     double a[12];
     double sum=0;
     double b[12];
     cout<<"please input the rainfall of the 12 months:\n";
     for(int i=0;i<12;i++)
     {
         cin>>a[i];
         sum+=a[i];
     }
     for(int j=0;j<12;j++)
     {
         b[j]=(a[j]/sum);
     }
     for(int m=0;m<12;m++)
     {
         cout<<setw(2)<<m+1<<"<"<<setw(2)<<fun(b[m])<<"%) ";
         for(int k=0;k<fun(b[m]);k++)
             cout<<"#";
         cout<<endl;
     }
     system("pause");
}
int fun(double s)//四舍五入函数
{    
    if (s*100>int(s*100+0.5))
        return int(s*100);
    else
        return int(s*100)+1;
}
调用了一个四舍五入的函数.
...
....
回来同学说可以更简单得解决,恍然大悟呀..直接强制转换了.........
#include<iostream>
using namespace std;
#include<iomanip>
int main()
{
     double a[12];
     double sum=0;
     int  b[12];
     cout<<"please input the rainfall of the 12 months:\n";
     for(int i=0;i<12;i++)
     {
         cin>>a[i];
         sum+=a[i];
     }
     for(int j=0;j<12;j++)
     {
         b[j]=int((a[j]/sum)*100+0.5);
     }
     for(int m=0;m<12;m++)
     {
         cout<<setw(2)<<m+1<<"<"<<setw(2)<<b[m]<<"%) ";
         for(int k=0;k<b[m];k++)
             cout<<"#";
         cout<<endl;
     }
     system("pause");
}
...
后来百度了以下,还有其他很多方法,就不一一列举了.
	
posted on 2011-06-03 17:26 
DoubleW 阅读(2609) 
评论(2)  编辑 收藏 引用