gpt4 book ai didi

c++ - 编译简单的 C++ 程序时出现问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:17:30 26 4
gpt4 key购买 nike

有人向我提供了这个简单的 C++ [我认为] 程序来研究可以存储的 int 的最大大小:

#include <limits.h>
#include <iostream>

void main ( int argc , char * argv[])

{

cout << "INT_MAX " << INT_MAX << endl ;
cout << "INT_MAX +1 = " << INT_MAX + 1 << endl ;
cout << "INT_MAX -1 = " << INT_MAX - 1 << endl ;

cout << "INT_MAX / INT_MAX " << INT_MAX /INT_MAX << endl ;
cout << "(INT_MAX +1) / INT_MAX " << (INT_MAX +1) /INT_MAX << endl;
cout << "(INT_MAX -1) / INT_MAX " << (INT_MAX -1) /INT_MAX <<endl;
cout << "INT_MAX / (INT_MAX +1) " << INT_MAX /(INT_MAX+1) <<endl;
cout << "INT_MAX / (INT_MAX -1) " << INT_MAX /(INT_MAX -1) <<endl;

}

我正在尝试编译:

gcc -o int_max int_max.cpp

但是我得到以下错误:

int_max.cpp:4: error: '::main' must return 'int'
int_max.cpp: In function 'int main(int, char**)':
int_max.cpp:8: error: 'cout' was not declared in this scope
int_max.cpp:8: error: 'endl' was not declared in this scope
int_max.cpp:9: warning: integer overflow in expression
int_max.cpp:13: warning: integer overflow in expression
int_max.cpp:15: warning: integer overflow in expression

我尝试在 main 的末尾添加一个 return 0,但这没有帮助。知道我做错了什么吗?

P.S 这可能实际上是一个 C 代码片段,但我似乎记得讲师说它是 C++。

干杯

最佳答案

您正在使用 gcc 在扩展名为 .c 的文件中编译 C++ 代码?

// Use new C++ header files instead of their .h version.
#include <climits>
#include <iostream>

// cout and endl are declared in the std namespace.
using namespace std;

int main (int argc, char * argv[])
{
cout << "INT_MAX " << INT_MAX << endl ;
cout << "INT_MAX +1 = " << INT_MAX + 1 << endl ;
cout << "INT_MAX -1 = " << INT_MAX - 1 << endl ;

cout << "INT_MAX / INT_MAX " << INT_MAX /INT_MAX << endl ;
cout << "(INT_MAX +1) / INT_MAX " << (INT_MAX +1) /INT_MAX << endl;
cout << "(INT_MAX -1) / INT_MAX " << (INT_MAX -1) /INT_MAX <<endl;
cout << "INT_MAX / (INT_MAX +1) " << INT_MAX /(INT_MAX+1) <<endl;
cout << "INT_MAX / (INT_MAX -1) " << INT_MAX /(INT_MAX -1) <<endl;

return 0;
}

并使用g++编译。

关于c++ - 编译简单的 C++ 程序时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2184421/

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