首页 > 其他 > 详细

输出,异常处理

时间:2020-07-13 19:30:59      阅读:42      评论:0      收藏:0      [点我收藏+]

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

技术分享图片

输出,异常处理

原文:https://www.cnblogs.com/a-runner/p/13294911.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!