输入输出工具库:
需提供:
#include<iostream>
using namespace std;
using namespace std的说明:
(1)using namespace std 表示 std 空间中的所有名称都可用
(2)若 using std::cout 表示 std 空间中只有 cout 名称可用
(3)当#include中没有.h 应当添加 using 语句来使 iostream 中的定义可用;若有 .h 则可得直接使用库中定义,故 using 用于避免不同类中的同名定义使用出错;
输出:cout (位于iostream中)
int main()
{
int t=10;
cout<<"";//可用于打印数值与字符串
cout<<"you"<<t<<"me";
cout<<endl;
cout << '$';//打印$字符
cout.put('$');//打印$字符
cout << endl;
}
endl (位于iostream中)表示:重起一行,因为cout不能使光标自动移到下一行,加入endl后便可以;(endl可确保程序继续运行前刷新输出)
“\n” 也能表示换行(原来C的方法)
注:默认情况下,cout 以十进制格式显示整数;
输入 cin
int main()
{
int t;
cin >>t;//将键盘输入值赋值给变量t
cout<<t;
cout<<endl;
}
数学计算函数库:
#include <iostream>
#include <cmath> //或者math.h
using namespace std;
int main()
{
int t,t4;
double t2,t3;
cin >> t;
t2 = sqrt(t);//开二次根号
t3 = pow(t2, 2);//t2的2次方
t4 = rand();//随机整数
cout << t <<" "<<t2<<" "<<t3<<" "<<t4;
cout << endl;
}
还在继续学习补充中
输出格式
int n = 141;
//1) 分别以十六进制、十进制、八进制先后输出 n
cout << "1)" << hex << n << " " << dec << n << " " << oct << n << endl;
double x = 1234567.89, y = 12.34567;
//2)保留5位有效数字
cout << "2)" << setprecision(5) << x << " " << y << " " << endl;
//3)保留小数点后面5位
cout << "3)" << fixed << setprecision(5) << x << " " << y << endl;
//4)科学计数法输出,且保留小数点后面5位
cout << "4)" << scientific << setprecision(5) << x << " " << y << endl;
//5)非负数显示正号,输出宽度为12字符,宽度不足则用 * 填补
cout << "5)" << showpos << fixed << setw(12) << setfill('*') << 12.1 << endl;
//6)非负数不显示正号,输出宽度为12字符,宽度不足则右边用填充字符填充
cout << "6)" << noshowpos << setw(12) << left << 12.1 << endl;
//7)输出宽度为 12 字符,宽度不足则左边用填充字符填充
cout << "7)" << setw(12) << right << 12.1 << endl;
//8)宽度不足时,负号和数值分列左右,中间用填充字符填充
cout << "8)" << setw(12) << internal << -12.1 << endl;
cout << "9)" << 12.1 << endl;
- 四舍五入法一:
1.引入头文件 #include<iomanip>
2.输出用固定格式
cout<<setiosflags(ios::fixed)<<setprecision(0)<<result<<endl;
//将result保留0位小数,四舍五入后输出。
round(x)
函数:(四舍五入最简便)
对于小数而言,round()
函数仅仅保留到整数位,即仅仅对小数点后一位四舍五入
手写round()
函数原理
#include<stdio.h>
double round(double x)
{
return (int)(x+0.5);
}
左值与右值
- 左值和右值:
- 左值是指那些在表达式执行结束后依然存在的数据,也就是持久性的数据;
- 右值是指那些在表达式执行结束后不再存在的数据,也就是临时性的数据。