我正在解决 Project Euler 上的问题 9 .在我的解决方案中,我使用“goto”语句来打破两个 for 循环。问题如下:
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
我的解决方案是 c++:
int a,b,c;
const int sum = 1000;
int result = -1;
for (a = 1; a<sum; a++){
for (b = 1; b < sum; b++){
c = sum-a-b;
if (a*a+b*b == c*c){
result = a*b*c;
goto found;
}
}
}
found:
std::cout << "a:" << a << std::endl;
std::cout << "b:" << b << std::endl;
std::cout << "c:" << c << std::endl;
std::cout <<"Result:" << result << std::endl;
由于“goto”语句在 c++ 程序员中不是很流行,我想知道这是否可以被认为是“goto”的合理使用。或者,对于不需要“goto”的问题,是否有更好的解决方案。我的意思不是一个解决方案,它只是避免“goto”,而是以改进算法的方式避免“goto”。
最佳答案
return
是一个“结构化”goto
,许多程序员觉得它更容易接受!所以:
static int findit(int sum, int* pa, int* pb, int* pc)
{
for (int a = 1; a<sum; a++) {
for (int b = 1; b < sum; b++) {
int c = sum-a-b;
if (a*a+b*b == c*c) {
*pa = a; *pb = b; *pc = c;
return a*b*c;
}
}
return -1;
}
int main() {
int a, b, c;
const int sum = 1000;
int result = findit(sum, &a, &b, &c);
if (result == -1) {
std::cout << "No result!" << std::endl;
return 1;
}
std::cout << "a:" << a << std::endl;
std::cout << "b:" << b << std::endl;
std::cout << "c:" << c << std::endl;
std::cout <<"Result:" << result << std::endl;
return 0;
}
关于c++ - 使用 goto 是打破两个循环的合法方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1024361/