系统函数
C++的系统库中提供了几百个函数可供程序员使用,例如:
求平方根函数(sprt)
求绝对值函数(abs)
使用系统函数时要包含相应的头文件,例如:
cmath
例 3-17 系统函数应用举例
题目:
从键盘输入一个角度值,求出该角度的正弦值、余弦值和正切值。
分析:
系统函数中提供了求正弦值、余弦值和正切值的函数:sin()、cos()、tan(),函数的说明在头文件 cmath 中。
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159265358979;
int main() {
double angle;
cout << "Enter a angle: ";
cin >> angle;//输入角度值
double radian = angle * PI/180;//转为弧度;
cout << "sin(" << angle << ")= " << sin(radian) << endl;
cout << "cos(" << angle << ")= " << cos(radian) << endl;
cout << "tan(" << angle << ")= " << tan(radian) << endl;
return 0;
}
斐波那契级数
#include <iostream>
using namespace std;
int fib(int n);
int main() {
int n,answer;
cout << "Enter number: ";
cin >> n ;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n <<"th Fibonacci number " <<"\n";
return 0;
}
int fib(int n){
cout << "Processing fib(" << n << ")....";
if(n < 3){
cout << "Return 1!\n";
return 1;
}
else{
cout << "Call fib(" << n-2 <<")and fib(" << n-1 <<").\n";
return (fib(n-2)+fib(n-1));
}
}
理解过程:
重载函数实验
例 判断大小
需要注意的是双精度数的比较
#include <iostream>
#include <cmath>
using namespace std;
int max1(int a,int b){
if(a > b){
return a;
}
else{
return b;
}
}
int max1(int a,int b,int c){
return max1(max1(a,b),c);
}
double max1(double a,double b){
//判断两个双精度数的最大值,由于存储方式,不能简单的通过比较来得到结果
//常见的处理方式:用来比较两个浮点数近似相等的方法
if(abs(a-b > 1e-10)){
return a;
}
else{
return b;
}
}
double max1(double a,double b,double c){
return max1(max1(a,b),c);
}
int main() {
int a,b,c;
cout <<"Enter three integers:";
cin >> a >> b >> c;
cout <<"max of "<< a <<" , "<< b << " is " << max1(a,b) << endl;
cout <<"max of "<< a <<" , " << b <<" , " << c << " is " << max1(a,b,c) << endl;
cout << "\n\n";
double x,y,z;
cout <<"Enter three doubles:";
cin >> x >> y >> z;
cout <<"max of "<< x <<" , "<< y << " is " << max1(x,y) << endl;
cout <<"max of "<< x <<" , "<< y << " , " << z << " is " << max1(x,y,z) << endl;
return 0;
}