1

So school has started and I am a little rusty on my Coding, I went to my professor and according to him I am close, and I have inched even closer I believe, but I am stuck.

The assignment is mainly for us to understand how to use "Vi" in linux, with a small coding assignment going along with it so we can code in Vi.

This is what we need to do, ask the user for a positive number, once the positive number is given we need to determine all the Pythagorean Triples that are possible for numbers up to equal to the given number.

So far this is what I have...

#include <stdio.h>

int main(void)
{

    int x = 0, y = 0, z = 0, n;
    int count = 0;

    printf("Please Enter A Positive Integer: \n");
    scanf("%d", &n);

    while (z <= n)
    {
        while (y < z)
        {
            while (x < y)
            {
                if (x * x + y * y == z * z)
                {
                    printf("%d: \t%d %d %d\n", ++count, x, y, z);
                }
                x += 1;
            }
            y += 1;
        }
        z += 1;
    }

Now if I enter anything 5 or higher I get a correct triple "3 4 5"

Please Enter A Positive Integer: 25
1:  3 4 5

But no matter how high I go this is as far as I get any tips?

4

3 回答 3

1

您需要在每个循环期间重置 x 和 y 的值:)。你所拥有的大致是这样的:

for(z = 0; z <=n; z++)
    for(; y < z; y++)
        for(; x < y; x++)

相反,您需要在每次到达循环时重置 x 和 y,因此:

while(z <= n) {
    y = 0;
    while(y < z) {
        x = 0;
        //...
于 2013-09-10T20:22:13.840 回答
1

您不会在外部循环的后续迭代中重置x和。您可能想考虑循环而不是循环。y0forwhile

for (z = 0; z <= n; z++)
{
    for (y = 0; y < z; y++)
    {
        for (x = 0; x < y; x++)
        {
            if (x * x + y * y == z * z)
            {
                printf("%d: \t%d %d %d\n", ++count, x, y, z);
            }
        }
    }
}
于 2013-09-10T20:22:29.360 回答
1

做一点调试。在您的 pythagorean 测试中添加 else 子句,以查看您实际测试的值;

if (x * x + y * y == z *  {
    printf("%d: \t%d %d %d\n", ++count, x, y, z);
} else {
    printf("NOT PYTH: %d: \t%d %d %d\n", ++count, x, y, z);
}

这将导致您遇到问题。

于 2013-09-10T20:32:00.900 回答