c++ - 使用 goto 是打破两个循环的合法方式吗?

标签 c++ goto

我正在解决 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/

相关文章:

c++ - 在 std::cout 中使用单引号打印字符串实际上打印的是数字

c++ - OpenCV 中的 Matlab Conv2 等效项

javascript - 在 JavaScript 中使用相同的代码两次

c# - 如何取消在 C# Winforms 应用程序中执行长时间运行的异步任务

Delphi:在这种情况下 Goto 不被认为是有害的吗?

c++ - 设置 3d 空间中对象的方向

c++ - 1字节无符号整数C++

c++ - 获取特征矩阵元素类型的好方法

perl - 在 perl 中调用 --> goto &fun($val) 或 fun($val) 哪个更有效?

带有字符串流标识符的 C++ goto