您的位置:首页 > 编程语言 > C语言/C++

C++学习记录(20180212)

2018-02-12 15:59 295 查看
1.格式化控制台输出
要结果显示两位小数
#include <iomanip>(流操作函数包含在此头文件中)

double amount = 12618.98;
double interestRate = 0.0013;
double interest = amount * interestRate;

cout << "Interest is " << fixed << setprecision(2) << interest << endl;

//fixed 显示指定小数位数的浮点数;setprecision(n) 设定一个浮点数的精度
double number = 12.34567;
cout << setprecision(3)<<number<<" "
        <<setprecision(4)<<number<<" "

        <<setprecision(5) << number<<" "

        <<setprecision(6)<<number<<endl;

//setprecision 操作的作用是直到精度改变之前,一直保持效果。
double number = 12.34567;
cout<<setprecision(3)<<number<<" ";
cout<<9.34567<<" "<<121.3457<<" "<<0.2367<<endl;

//showpoint 操作
cout <<setprecision(6);
cout<<1.23<<endl;
cout<<showpoint<<1.23<<endl;
cout<<showpoint<<123.0<<endl;

//setw(width)
指定输出的最小列数
cout<<setw(8)<<"C++"<<setw(6)<<101<<endl;
cout<<setw(8)<<"Java"<<setw(6)<<101<<endl;
cout<<setw(8)<<"HTML"<setw(6)<<101<<endl;

//右对齐
cout<<right;
cout<<setw(8)<<1.23<<endl;
cout<<setw(8)<<351.34<<endl;

//左对齐
cout<<left;
cout<<setw(8)<<1.23;
cout<<setw(8)<<351.34<<endl;
//写入文件
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream output;

// Create a file
output.open("numbers.txt");

//Write numbers
output << 95 << " " << 56 << " " << 34;

//close file
output.close();

cout << "Done" << endl;

    return 0;
}

//读入文件
#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ifstream input;
input.open("numbers.txt");
double score1;double score2;double score3;
input >> score1 >> score2 >> score3;
cout << "Total score is " << score1 + score2 + score3 << endl;
input.close();
cout << "Done" << endl;

    return 0;

}

实例一:计算五边形面积
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
const double pi = 3.1415926;
double s, Area,r;
cout << "Enter the length from the center to a vertex: " << endl;
cin >> r;
s = 2 * r*sin(36*pi/180);
Area = (5 * s*s) / (4 * tan(36*pi/180));
cout << "The area of the pentagon is " << fixed << setprecision(2) << Area << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: