有人可以帮助我了解标签和转到功能的工作原理吗?
我对 C++ 编程完全陌生,所以这段代码实际上可能有很多错误,我不确定。但是我遇到的问题是我的代码开头有一个标签 (START:),我goto稍后会引用它。该goto函数本身似乎没有问题,但是在我第一次使用 START 标签的地方,我收到一个错误,提示"this declaration has no storage class or type specifier". 不确定我是否只是不明白标签/goto 是如何工作的,或者功能void是否导致了问题,或者是什么。就像我说的,这对我来说都是全新的。
#include <iostream>
#include <string>
using namespace std;
double weight;
string planet;
double newWeight;
START:
void getUserInput() {
cout << "Enter your weight and a planet: ";
cin >> weight >> planet;
}
void convertInputToPlanetType() {
if (planet == "Mercury") {
newWeight = weight * 0.4155;
}
else if (planet == "Venus") {
newWeight = weight * 0.8975;
}
else if (planet == "Earth") {
newWeight = weight;
}
else if (planet == "Moon") {
newWeight = weight * 0.166;
}
else if (planet == "Mars") {
newWeight = weight * 0.3507;
}
else if (planet == "Jupiter") {
newWeight = weight * 2.5374;
}
else if (planet == "Saturn") {
newWeight = weight * 1.0677;
}
else if (planet == "Uranus") {
newWeight = weight * 0.8947;
}
else if (planet == "Neptune") {
newWeight = weight * 1.1794;
}
else if (planet == "Pluto") {
newWeight = weight * 0.0899;
}
else {
cout << "Error: Please enter a valid planet name, starting with a capital letter (ie. 'Earth')";
goto START;
}
}
void outputWeight() {
cout << "On " << planet << " you would weigh " << newWeight << " pounds!" << endl;
}
回答
您只能goto在同一功能中使用标签。您不能使用它在功能之间跳转,因为您似乎正在尝试这样做。
事实上,goto一般来说是一种糟糕的程序设计方式。作为初学者,您可能应该忘记它的存在。在某些特殊情况下,有些人认为它比替代方案更好,但是需要相当多的专业知识才能做出正确的判断,无论如何,您的情况绝对不是其中之一。
考虑如何重新设计您的程序以使用while或来获得所需的效果do/while。convertInputToPlanetType返回一个指示转换是否成功的值可能会有所帮助,这样getUserInput可以判断是否再次询问用户。
作为旁注,还要考虑如何重新设计程序以不使用全局变量,而是通过函数参数传递数据。全局变量是另一种语言特性,作为初学者,您可能应该忽略它。