2015-10-19 49 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