我的三角三元组程序有一个问题

There is an issue with my triangle triples program

本文关键字:有一个 问题 程序 三元组 三角 我的      更新时间:2023-10-16

我的程序应该列出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;
}

下面的行不会达到您的预期:

// 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) {

在创建三元组之前,强制对它们进行排序。斜边总是最后一条,最短的边总是第一条。(我们不需要担心(a,a,b),因为这样的积分组合是不存在的。

因此,对于解三重(a,b,c),应该总是真的,a<b<c、 a>0,b>0,c>0。

简单。:)

您很可能会对某些三元组进行两次计数。如果你检查你的输出,你肯定会看到"3,4,5"重复了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。一定要按照胡永涛的回答来解决这个问题。

计数器未初始化为0。你像三角形一样跳过的逻辑在哪里?