C++基础教程10-数学运算

文章目录

  • 1.数学函数
  • 2.用数学函数进行公式运算
  • 3.随机数
  • 篇章

1.数学函数

#include 
using namespace std;
#include  //引入数学函数的头文件 ,采用C语言的风格 
#define pi 3.1415926 //定义一个常量π 
int main()
{
     
	printf("整数运算:1+2=%d",1+2); //整数运算,%d是将数字字符串转成整数字符串,进行自动地运算
	printf("\n"); //换行 
	printf("浮点数运算:1.0/3=%.2f",1.0/3); //保留小数后两位,结果只识别浮点型,所以我们要将其他一个数换成浮点型 
	printf("\n"); //换行 
	cout << "平方数:pow(3, 2) :" << pow(3, 2) << endl; //3的平方为9 
	cout << "开方数:sqrt(9) :" << sqrt(9) << endl;     //9开方之后为3 
	cout << "整数的绝对值:abs(-10)  :" << abs(-10) << endl; //10
	cout << "浮点数的绝对值:fabs(-10.6)  :" << abs(-10.6) << endl; //10.6
    cout << "取一个小于或等于参数的最大整数:floor(8.9) :" << floor(8.9) << endl;//8<8.9 
    cout << "取一个小于或等于参数的最大整数:floor(-8.9) :" << floor(-8.9) << endl;//-9<-8.9 
    cout << "指数函数:log10(100) :" << log10(100) << endl; //10的平方是100,求出的指数是平方根 
    cout << "正弦函数:sin(30*pi/180) :" << sin(30*pi/180) << endl;//相当于数学中正弦30度,括号里的是弧度数,所以才要加上1弧度的式子 
	cout << "余弦函数:cos(60*pi/180) :" << cos(60*pi/180) << endl;//同理可得 
	cout << "正切函数:tan(45*pi/180) :" << tan(45*pi/180) << endl;//同理可得 
  	cout << "取一个直角三角形的斜边:hypot(3, 4) :" <<  hypot(3, 4) << endl; //3的平方+4的平方=25,25再开方,就变成了5 
	return 0; 
} 

运行效果
C++基础教程10-数学运算_第1张图片

2.用数学函数进行公式运算

C++基础教程10-数学运算_第2张图片

#include 
using namespace std;
#include  //引入数学函数的头文件 ,采用C语言的风格 
int main()
{
     
	//第一种方法:cout 
	int a=1;
	float b=2*sqrt(3);
	float c=4-0.5;
  	cout << (float)a+b/c << endl;
  	
  	//第二种方法:printf 
  	printf("%.5f",1+2*sqrt(3)/(4-0.5));
  	
	return 0;
} 

运行效果
C++基础教程10-数学运算_第3张图片

3.随机数

随机函数与时间函数搭配使用

#include //输入输出 
#include    //获取time函数 
#include  //获取随机函数 
using namespace std;
int main ()
{
     
   srand( (unsigned)time( NULL ) );   // 设置种子
   for(int i = 0; i < 3; i++ ) /* 生成 3 个随机数 */
   {
      
      int r= rand();  // 生成实际的随机数
      cout << r << "\t"; //打印随机数 
   }
   cout << endl; 
   for(int i = 0; i < 3; i++ ) /* 生成 3 个随机数 */
   {
      
      int r= rand()%100+1;  // 生成1-100的随机数
      cout << r << "\t"; //打印随机数 
   }
   cout << endl; 
   for(int i = 0; i < 3; i++ ) /* 生成 3 个随机数 */
   {
      
      int r= rand()%100;  // 生成0-100的随机数
      cout << r << "\t"; //打印随机数 
   }
   return 0;
}

运行效果
C++基础教程10-数学运算_第4张图片
随机函数的使用

#include //输入输出 
#include  //获取随机数
//如果没有ctime的头文件,生成的随机数就是固定的,不管编译多少次,结果都是一样的 
using namespace std;
int main ()
{
     
   for(int i = 0; i < 3; i++ ) /* 生成 3 个随机数 */
   {
      
      int r= rand()%100+1;  // 生成实际的随机数
      cout << r << "\t"; //打印随机数 
   }
   return 0;
}

运行效果
C++基础教程10-数学运算_第5张图片

篇章

上一篇:C++基础教程9-二维数组

下一篇:C++基础教程11-函数

你可能感兴趣的:(C++,c++)