-1

I am trying to make a program which would generate 3 sides given following input: longest allowed hypotenuse and number of triangles required. The sides can be only integers. The program I have written just hangs on me and does not return any output. If you are to downvote me explain why.

#include <iostream>
#include <cmath>
#include <cstdlib>

int generator(int number, int hypoth){

    int a,b,c;

    while (number>0){
        c=rand()%(hypoth-1)+1;
        for (a=1;a<hypoth-2;a++){
            for (b=1;pow(a,2)+pow(b,2)<=pow(c,2); b++){
                if (pow(a,2)+pow(b,2)==pow(c,2)){
                    std::cout<<"sides: "<<a<<" "<<b<<" "<<c<<std::endl;
                    number--;
                }
            }
        }
    }
    return 0;
}

int main(){
    int triangle_number, hypothenuse;
    std::cout << "How many triangles to generate? ";
    std::cin >> triangle_number;
    std::cout << "How long is max hypothenuse?";
    std::cin >> hypothenuse;
    generator(triangle_number, hypothenuse);
    return 0;
} 

If you think I should improve my algorithm please hint me in right direction. Thank you for your time.

  • 5
    Welcome to Stack Overflow! It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: **[How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver Jun 01 '16 at 20:13
  • what input did you use? maybe it just takes too long to finish – 463035818_is_not_an_ai Jun 01 '16 at 20:17
  • @tobi303 input 1,6 (1 triangle, longest hypotenuse 6) leads to hanging too. Also if it would find an answer it would post it right away so I doubt that it is the case. – Sleepycoder Jun 01 '16 at 20:25
  • I think the problem is: c=rand()%(hypoth-1)+1; as it can take a while until it guesses a large enough number which was not guessed before. – Sleepycoder Jun 01 '16 at 20:38

1 Answers1

2

The code you provided works fine on my machine: inputting 1 and 6 gives output sides: 3 4 5.

However, the problem probably arises from the line: pow(a,2)+pow(b,2)==pow(c,2). pow returns a double. Comparing floating-point numbers for equality is slippery, and practically never a good idea, since it's likely to be off by a tiny amount, and be false.

Replace it with a*a + b*b == c*c (and the condition within the for loop just above with a*a + b*b <= c*c).

Nick Matteo
  • 4,453
  • 1
  • 24
  • 35