我正在使用 Eclipse C++ 来学习编程,但由于未在此范围内声明变量,我无法让程序完全编译。我承认我很糟糕,而且是编程新手,但是有人可以提供任何帮助吗?例如,
/*
datatypes.cpp
Aug 25, 2014
gauvey42684
*/
#include <iostream>
using namespace std;
int main()
{
char letter = 'a';
short age = 10;
int count = 575;
long numStars = 985467528;
float pi = 3.14;
double price = 89.65
string season = "summer";
cout<<"letter"<<letter<<endl;
cout<<"age"<<age<<endl;
cout<<"count"<<count<<endl;
cout<<"Number of Stars in the Sky"<<numStars<<endl;
cout<<"pi: "<<pi<<endl;
cout<<"price: $"<<price<<endl;
cout<<season<<season<<endl;
return 0;
}
在这行代码中,最后一个 cout 处的变量 season 没有在此范围内声明。
再举个例子,
/*
C++lesson.cpp
Aug 22, 2014
gauvey42684
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// variables
double mpg, distance, gallons, pricepergallon, totalcost
//output using insertiuon operator
cout<<"Enter mpg"<<endl;
//input using extraction operator
cin>>mpg;
cout<<"Enter Distance in miles"<<endl;
cin>>distance;
cout<<"Enter Price for one gallon of gas"<<endl;
cin>>pricepergallon;
//calculate gallons needed
gallons=distance/mpg;
//calculate total cost
totalcost=gallons * pricepergallon;
cout<<"Total Trip Cost: $"<<fixed<<setprecision(2)<<totalcost<<endl;
return 0;
}
在此程序中,totalcost 也不能在此范围内声明。有什么建议吗?
最佳答案
语法错误往往会使编译器感到困惑。
当我编译上面的代码时,我得到的第一条消息是关于缺少分号的。具体来说,编译器 (g++ 4.8.2) 提示:
c.cpp: In function ‘int main()’:
c.cpp:16:5: error: expected ‘,’ or ‘;’ before ‘string’
string season = "summer";
^
c.cpp:24:11: error: ‘season’ was not declared in this scope
cout<<season<<season<<endl;
^
第一个错误是语法错误,由缺少 ;
引起。编译器变得如此困惑(更准确地说,它失去了其内部数据结构为源文件建模的能力),以至于它不知道应该使用逗号还是分号。它甚至无法识别这条线
string season = "summer";
作为变量声明——这就是为什么它后来将其报告为未声明的标识符。
您的第二个示例中发生了非常相似的事情。你忘记了分号
double mpg, distance, gallons, pricepergallon, totalcost
这里有两个教训:
首先,在发布有关编译失败的问题时,请始终将编译器生成的确切错误消息复制并粘贴到问题中。不要总结消息所说的内容,向我们展示。在这种情况下,您遗漏了重要信息。
其次,如果您的编译器报告语法错误,请直接转到消息中报告的行。研究那行代码和它之前的几行代码。查找缺少的标点符号、拼写错误等。语法错误的错误消息可能提供信息,也可能不提供信息——但它应该告诉您编译器检测到错误的确切位置。 (对编译器如何解析源代码有一些了解会有所帮助,但这并不是真正必要的。)如果在第一个语法错误之后还有其他错误消息,不要太担心理解它们;先修正语法再重新编译。
(根据编译器的不同,语法错误消息可能包含也可能不包含“语法”一词。通常它会告诉您编译器希望在特定点看到什么标记或标记。其他错误是 语义 错误,如未声明的标识符、应用具有错误操作数类型的运算符等)
关于c++ - 在 Eclipse IDE C++ 中未在此范围内声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510783/