2015-10-19 24 views
-1

到目前为止,该程序将打印所有三元组,并告诉您输入的数字是否没有三元组。我需要它在列出所有三元组之后再次打印C值最高的三元组。 Example I/O for this project打印Highest Pythagorean Triple - C

#include <stdio.h> 

void main() 
{ 

    int a = 0, b = 0, c = 0, n; 
    int counter = 0; // counter for # of triples 

    printf("Please Enter a Positive Integer: \n"); //asks for number 
    scanf_s("%d", &n); //gets number 

    for (c = 0; c < n; c++) //for loops counting up to the number 
    { 
     for (b = 0; b < c; b++) 
     { 
      for (a = 0; a < b; a++) 
      { 
       if (a * a + b * b == c * c) //pythag to check if correct 
       { 
        printf("%d: \t%d %d %d\n", ++counter, a, b, c); //prints triples in an orderd list 

       } 
       else if (n < 6) // if less than 6 - no triples 
       { 
        printf("There is no pythagorean triple in this range"); 
       } 
      } 
     } 
    } 
    getch(); //stops program from closing until you press a keys 
} 

如果我输入15分成N它将打印:

3 4 5 
6 8 10 
5 12 13 

所以最后三重它打印总是有C的最高值(5 12 13),但我需要打印声明说特定三重最高。

+0

不要张贴外部链接或图像,除非绝对必要! – Olaf

+0

您可以简单地使用3个额外的变量来追踪C值最大的三元组。无论您是倒数还是倒数,您仍然需要这3个变量。 –

+0

@ChronoKitsune你能否解释一下我可以如何实现它们来跟踪价值?我非常喜欢新手,谢谢! – Miragee13

回答

0

请试试这个,我相信你可以改进,但它可以工作,但我没时间清理它,所以玩得开心!

#include <stdio.h> 

void main() 
{ 

    int a = 0, b = 0, c = 0, n; 
    int counter = 0;  // counter for # of triples 
    int triple_sum[6]; 
    int sums = 0; 
    int triple_high_sum = 0; 
    int triple_high_index = 0; 

    printf("Please Enter a Positive Integer: \n"); //asks for number 
    scanf("%d", &n);  //gets number 

    for (c = 0; c < n; c++) //for loops counting up to the number 
    { 
    for (b = 0; b < c; b++) 
    { 
     for (a = 0; a < b; a++) 
     { 
    if (a * a + b * b == c * c) //pythag to check if correct 
    { 
     printf("%d: \t%d %d %d\n", counter, a, b, c); 
    //prints triples in an orderd list 
     triple_sum[counter++] = a + b + c; 

    } 
    else if (n < 6) // if less than 6 - no triples 
    { 
     printf("There is no pythagorean triple in this range"); 
     break; 
    } 
     }    // endfor 

    }    // endfor 
    } 

    sums = --counter; 
    triple_high_sum = -1; 
    if (sums) 
    while (sums > -1) 
    { 
     printf("\ntriple_sum %d == %d", sums, triple_sum[sums]); 
     if (triple_sum[sums] > triple_high_sum) 
     { 
    triple_high_sum = triple_sum[sums]; 
    triple_high_index = sums; 
     } 
     sums--; 
    }    // endwhile 

    if (triple_high_sum > -1) 
    printf("\nThe triple index with the largest value is %d", 
     triple_high_index); 

    getchar();   //stops program from closing until you press a keys 
} 
     //stop