使用goto合法的方式来打破两个循环? [英] Is using goto a legitimate way to break out of two loops?

查看:163
本文介绍了使用goto合法的方式来打破两个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决 Project Euler 上的问题9。在我的解决方案中,我使用goto语句来打破两个for循环。问题如下:

I am solving problem 9 on the Project Euler. In my solution I use a "goto" statement to break out of two for loops. The Problem is the following:


毕达哥拉斯三元组是一组三个自然数,abc,

A Pythagorean triplet is a set of three natural numbers, a b c, for which,

a ^ 2 + b ^ 2 = c ^ 2

a^2 + b^2 = c^2

例如,3 ^ 2 + 4 ^ 2 = 9 + 16 = 25 = 52。

For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.

只有一个毕加索复合三元组,其中a + b + c = 1000.
查找产品abc。

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

我的解决方案在c ++中:

My solution is in 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以改进算法的方式。

Since "goto" statements are not very popular among c++ programmers, i would like to know, if this could be considered a reasonable use of "goto". Or if there is a better solution for the problem that doesn't need "goto". By that I don't mean a solution which just avoids "goto", but which avoids "goto" in a way that improves the algorithm.

推荐答案

return 是一个结构化 goto ,许多程序员都觉得更容易接受!因此:

return is a "structured" goto which many programmers find more acceptable! So:

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;
}

这篇关于使用goto合法的方式来打破两个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆