【发布时间】:2015-06-04 18:04:19
【问题描述】:
我一直在开发一个基于控制台的计算器应用程序,我想使用 2 个函数来让它看起来更干净(我不希望 main 有太多行),所以我决定使用 goto 跳转从 main 到我的箔函数,然后另一个 goto 跳回到 main 的开头。我只是想知道这样做是否不安全。谢谢:)
void foileq()
{
int a, b, c, d;
printf("Enter the 4 numbers\n");
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cout << a * c << " " << a * d << " " << b * c << " " << b * d << endl;
}
int main()
{
float a, b;
string type = "";
BEGIN:
{
while (1)
{
printf("Add,subtract,multiply,divide,foil,power?\n");
cin >> type;
if (type == "foil")
{
goto FOIL;
continue;
}
else
{
printf("Enter A number\n");
cin >> a;
printf("Enter another number\n");
cin >> b;
if (strcmp(type.c_str(), "add") == 0)
printf("%.2f\n", a + b);
else if (strcmp(type.c_str(), "subtract") == 0)
printf("%.2f\n", a - b);
else if (strcmp(type.c_str(), "multiply") == 0)
printf("%.2f\n", a * b);
else if (strcmp(type.c_str(), "divide") == 0)
printf("%.2f\n", a / b);
else if (strcmp(type.c_str(), "power") == 0)
printf("%.2f\n", pow(a, b));
}
}
}
FOIL:
foileq();
goto BEGIN;
}
【问题讨论】:
-
在这种情况下,我(不讨厌 goto)认为它很糟糕,主要是无限循环
-
float main()??? -
请提供一个适当的例子 - 请参阅@NathanOliver 评论(对于否决票来说太糟糕了)
-
是的,我不确定为什么我将它从通常的更改为浮动,我想 b/c 我在函数内部使用了浮动,但是是的,没有必要这样做。我看不出这个例子是怎么不合适的,因为它编译和运行良好,即使它通常是 int/void。
-
不要使用
goto向后跳!这是规则之一,那些蹩脚的 MISRA 标准是正确的。
标签: c++ calculator