C++数字
这个~~~都不打算写的,但是这里面有一个随机数,这个还是比较重要的,那就讲一下吧。
C++定义数字
直接上代码吧,这个比较简单
#include <iostream>
using namespace std;
int main ()
{
// 数字定义
short s;
int i;
long l;
float f;
double d;
// 数字赋值
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// 数字输出
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
运行结果就是这样的
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
C++数学运算
在C++中我们有时候会涉及到一些数学的知识,比如说cos sin tan等等,这种呢我们一般要先导入数学的头文件,也就是先导库,<cmath>就是C++中的数学库。
序号 | 函数 & 描述 |
---|---|
1 | double cos(double); 该函数返回弧度角(double 型)的余弦。 |
2 | double sin(double); 该函数返回弧度角(double 型)的正弦。 |
3 | double tan(double); 该函数返回弧度角(double 型)的正切。 |
4 | double log(double); 该函数返回参数的自然对数。 |
5 | double pow(double, double); 假设第一个参数为 x,第二个参数为 y,则该函数返回 x 的 y 次方。 |
6 | double hypot(double, double); 该函数返回两个参数的平方总和的平方根,也就是说,参数为一个直角三角形的两个直角边,函数会返回斜边的长度。 |
7 | double sqrt(double); 该函数返回参数的平方根。 |
8 | int abs(int); 该函数返回整数的绝对值。 |
9 | double fabs(double); 该函数返回任意一个浮点数的绝对值。 |
10 | double floor(double); 该函数返回一个小于或等于传入参数的最大整数。 |
来个代码试试水:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// 数字定义
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// 数学运算
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
运行结果如下
sin(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
C++随机数
随机数,字如其码,就是随机生成一个数字,这个就要使用到我们的两个库,一个是<ctime>,一个是<cstdlib>,废话不多。上代码!!!!
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main(){
int i,j;
//设置种子
srand((unsigned)time(NULL));
for (int i = 0; i < 10; ++i) {
j = rand();
cout << j<<endl;
}
}
运行结果