Вопрос

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?

Это было полезно?

Решение

You need to reset your values of x and y during each of your loops :). What you have is roughly this:

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

Instead you need to reset x and y each time their loops are reached, so:

while(z <= n) {
    y = 0;
    while(y < z) {
        x = 0;
        //...

Другие советы

You're not resetting x and y to 0 on subsequent iterations of the outer loops. You might want to think about for loops instead of while loops.

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);
            }
        }
    }
}

Do a little debugging. Add an else clause to your pythagorean test to see what values you're actually testing;

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);
}

This will lead you to your problem.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top