输出,异常处理

1. 计算三角形面积:

  首先判断 是否构成三角形,在进行判定。并抛出错误处理。

#include <iostream> 
#include <string> 
#include<cmath>
using namespace std; 
double floor(double x, double y, double z)
{
    double s = (x + y + z) / 2;
    double f;
    if ((x + y > z) && (x + z > y) && (y + z > x))
    {
        f = sqrt(s * (s - x) * (s - y) * (s - z));
    }
    else {
        throw "The number entered cannot form a triangle!!";
    }
    return f;
}
int main( ) 
{
    double x, y, z,area;
    cout << "please input three doubles of the traingle:" << endl;
    begin:
    cin >> x >> y >> z;
    try {
        area = floor(x, y, z);
        cout << "The area of the traingle is:" << area << endl;
    }
    catch (const char* s)
    {
        cout << s << endl;
        cout << "please again input three doubles of the traingle:" << endl;
        goto begin;
    }
return 0; }

 

2. 输出保留3位小数的程序,小数点对齐。

(1)控制符控制输出格式:

#include <iostream> 
#include <string> 
#include<cmath>
using namespace std; 

int main( ) 
{
    double x;
    while (cin >> x)
    {
        cout.setf(ios_base::showpoint);
        cout.setf(ios_base::fixed, ios_base::floatfield);
        cout.precision(3);
        cout.width(10);
        cout << x << endl;

    }
return 0; }

(2)流成员函数控制输出格式:

#include <iostream> 
#include <iomanip> 
#include<cmath>
using namespace std; 

int main( ) 
{
    double x;
    while (cin >> x)
    {
        cout << fixed << right;
        cout <<setw(14)<< setprecision(3) << x << endl;

    }
return 0; }

3.建立磁盘文件f1.dat,f2,dat:

(1)分别输入10个整数到两个磁盘文件中:

#include <iostream> 
#include <fstream> 
#include<cmath>
using namespace std; 
void write_num(ofstream& fout, ofstream& fout2)
{
    int x;
    for (int i = 0; i < 5; i++)
    {
        cin >> x;
        fout << x << ' ';
    }
    for (int i = 0; i < 5; i++)
    {
        cin >> x;
        fout2 << x << ' ';
    }
}
//void move_f1_to_f2(ofstream& fout, ofstream& fout2)
int main( ) 
{
    int x;
    ofstream fout,fout2;
    fout.open("f1.dat");
    fout2.open("f2.dat");
    write_num(fout, fout2);
return 0; }

(2):从f1.dat读取一行数据,放到f2.dat原有数据后面:

#include <iostream> 
#include <fstream> 
#include<string>
#include<cmath>
using namespace std; 
int main( ) 
{
    string x;
    ifstream fin;
    ofstream fout2;
    fin.open("f1.dat");
    fout2.open("f2.dat",ios_base::app);
    getline(fin, x);
    fout2 << x;
return 0; }

posted @ 2020-07-13 18:17  为红颜  阅读(212)  评论(0编辑  收藏  举报