cpp<1> library, input and output

Table of contents

1. Library

2. Input and output

1. Classic example: hello world

2. Input principle

Keyboard to buffer:

General mechanism of input function:

output

Issues involving saving decimals


Since the author has already written study notes for C, this series mainly supplements the differences between CPP and C.

1. Library

<iostream>  

<cstdio>

<iomanip> Output function library related to preserving decimals

<cmath>

2. Input and output

1. Classic example: hello world

#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World!\n"<<endl;//endl:换行
    system("pause");
    return 0;
}

2. Input principle

Keyboard ------->Buffer---->Input function

Keyboard to buffer:

Automatically enter the buffer when typing\n

General mechanism of input function:

1. Check whether there is data in the buffer

2.0, No: Read keyboard data

2.1, Yes: Read data in the buffer

1, scanf: will stop reading when encountering a space or carriage return

2, getchar: Read all data and end when EOF is encountered

(The buffer can be cleared through this principle)

//把缓冲区中的内容全读走
	while ( getchar() != '\n')
	{
		;
	}

3,cin: I will add more if I encounter it later.

output

Issues involving saving decimals

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
	double t; int n;
	cin >> t >> n;
	cout <<fixed<<setprecision(3)<<t/n<<endl<<n*2;
	return 0;
}

Small example: Find the area of ​​a triangle knowing the three sides

#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
double helon(double a, double b, double c);
int main()
{
	double a, b, c,ss;
	cin >> a >> b >> c;//输入三边长
	ss = helon(a, b, c);
	cout <<fixed<<setprecision(1) << ss << endl;//输出三角形面积
	system("pause");
	return 0;
}
double helon(double a, double b, double c)
{
	double p, s;
	p = (a + b + c) / 2;
	s = sqrt(p * (p - a) * (p - b) * (p - c));
	return s;
}

Guess you like

Origin blog.csdn.net/weixin_60787500/article/details/127654991