1、背景
现希望引用标准头文件来计算4的根号和平方,编写如下代码,但发现引入标准头文件错误。
#include <math>
#include <iostream>
using namespace std;
int main()
{
cout << "根号:" << sqrt(4) << endl;
cout << "平方:" << pow(4, 2) << endl;
return 1;
}
2、分析与修改
C语言一般通过#include <***.h>
引用标准库文件,而C++一般通过#include <c**>
引用标准库文件。#include <math>
中的math
即不是math.h
,也不是cmath
,故引用错误。
// 错误
#include <math>
// 修改
#include <math.h> // c
#include <cmath> // c++
修改后的正确结果: