gpt4 book ai didi

c++ - 真的需要吗?没有它编译

转载 作者:太空狗 更新时间:2023-10-29 19:52:13 26 4
gpt4 key购买 nike

所以,我有以下代码,它构建和运行完美,尝试了各种值,一切都很好。您会注意到我使用了 log10 函数,但没有包含 cmath 或 math.h。为什么它仍然可以正常构建和运行?那些图书馆真的需要吗?为什么/为什么不?跟我用visual studio有关系吗?比如,如果说我使用不同的 IDE 或命令提示符来编译它,它不会编译吗?

#include <iostream>
#include <iomanip>
using namespace std;

int main() {

cout << "Classify solutions as acidic or nonacidic" << endl<< endl;

//declaring double molar concentration
double mc = 1;

//using while and if statements to calculate pH in fixed notaion and acidic or nonacidic
while (mc != 0)
{
cout << "Please enter a molar concentration (or enter 0 to exit): ";
cin >> mc;

if (mc != 0)
{
cout << "Molar Conentration = " << scientific << mc << endl; //scientific notation

double pH = -log10(mc);
cout << "pH = " << fixed << setprecision(6) << pH << endl; //6 deciumals

if (pH > 7)
{
cout << "Nonacidic" << endl << endl;
}
else if (pH < 7)
{
cout << "Acidic" << endl << endl;
}
else
cout << "Neutral" << endl << endl;
}
}

//end program when inputing 0
cout << "End of Program" << endl;

return 0;
}

最佳答案

代码:

i = i++ + ++i;

可能编译没问题,但这并不是一个好主意:-)

最好为您使用的库函数包含 header 。这样做不会失去任何功能,但您确实保证该功能会正常工作(尽管存在误用)。


详 segmentation 析如下。

即使实现对此有所放松,标准也强制要求这样做。 C++11 17.6.2.2 Headers /3状态:

A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header.

gcc例如,编译器会提示你的代码:

xyzzy.cpp: In function 'int main()':
xyzzy.cpp:22:34: error: 'log10' was not declared in this scope
double pH = -log10(mc);
^

至于为什么VC++貌似违反了这个规则,这与头文件允许包含其他头文件这一事实有关。

如果您编译代码以生成预处理器输出(使用 /P ),您会发现其中隐藏着一行代码(至少在 VS2013 中是这样):

#line 1 "c:\\blah\\blah\\vc\\include\\cmath"

稍加分析就会发现以下包含层次结构:

iostream
istream
ostream
ios
xlocnum
cmath

( <xlocnum><locale> 使用的内部 header 之一,似乎需要 ldexp() 库中的 <cmath>,尽管可能还有其他 header )。

VC++ 确实提示以下代码这一事实进一步证明了这一点:

//#include <iostream>
using namespace std;

int main() {
double oneHundred = 100;
int two = log10 (oneHundred);
return two;
}

与:

error C3861: 'log10': identifier not found

但是当您取消对 iostream 的注释时,该错误就会消失包含线。


但是,如前所述,这不是您应该依赖的行为。如果您要使用库函数(或宏/模板/其他),需要包含正确的 header 。

否则你的程序编译正确只是一个意外。

关于c++ - <cmath> 或 <math.h> 真的需要吗?没有它编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29338108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com