我的三角形三元组程序存在问题

时间:2014-10-09 03:05:19

标签: c++

我的程序应该列出1-500之间的所有直角三角形三元组。它不应该重复相同的三角形。例如,3,4,5与4,3,5相同,只应显示第一个。我也应该在程序的最后有一个计数器,显示找到了多少个三角形。到目前为止,这就是我所拥有的。它当前没有显示正确数量的三角形,并且计数器无法正常工作。感谢

// Naming

int counter;

// For loops and nested for loops

{
       // Makes sure side A starts at 1 and is less than 500
for (int a = 1; a <= 500; a++)
{
       // Makes sure side B starts at 1 and is less than 500
    for (int b = 1; b <= 500; b++)
    {
       // Makes sure side C starts at 1 and us kess than 500
        for (int c = 1; c <= 500; c++)
        {
       // If A squared + B squared = C squared and C squared, A, and B --> 
       // are all less than or equal to 500 then display the answer
            if ((a*a)+(b*b) == c*c & a & b <= 500) {
            // This is my counter I cannot seem to get it to work properly
            // More info about counter at bottom
            counter++;
                cout << a << ", " << b << ", " << c << endl;
            }
        }
    }
}
}

cout << endl;
// Displaying counter
cout << counter << endl << endl ;

system("PAUSE");
return EXIT_SUCCESS;
}

4 个答案:

答案 0 :(得分:1)

以下行不符合您的期望:

// If A squared + B squared = C squared and C squared, A, and B --> 
// are all less than or equal to 500 then display the answer
    if ((a*a)+(b*b) == c*c & a & b <= 500) {
                             ^^^^^^^^^^^^

张它:

if ((a*a)+(b*b) == c*c && a <= 500 && b <= 500) {

ps:正如@ Code-Apprentice进一步评论的那样,a <= 500 && b <= 500循环已经保证for,因此它可以简化为:

if ((a*a)+(b*b) == c*c) {

答案 1 :(得分:1)

强制在创建三元组之前对其进行排序。斜边永远是最后的,最短的路将始终是第一个。 (我们不需要担心(a,a,b),因为这样的整体组合将不存在。

因此对于解决方案三(a,b,c),a&lt; a&lt; b&lt; c,a&gt; 0,b> 0,c> 0

易。 :)

答案 2 :(得分:0)

你最有可能计算两次三倍。如果你检查你的输出,你肯定会看到&#34; 3,4,5和#34;重复6次。事实上,每个三倍将重复6次。这表明快速解决方法是将您的计数器除以6。

或者,您可以通过使用外部循环来确定不重复任何三元组来定义内部循环的起点:

for (int a = 1; a <= 500; a++)
{
    // Makes sure side B starts at 1 and is less than 500
    for (int b = a + 1; b <= 500; b++)
    {
       // Makes sure side C starts at 1 and us kess than 500
        for (int c = b + 1; c <= 500; c++)

P.S。此外,if条件中的错误可确保计算每个数字组合,因此输出为625000000。请务必按照herohuyongtao's answer

中的说明进行修复

答案 3 :(得分:0)

计数器未初始化为0.您的逻辑在哪里跳过三角形?