Home > Software engineering >  Least common multiple for 3 numbers in C
Least common multiple for 3 numbers in C

Time:11-04

I've written some code to calculate LCM for 3 numbers. My question is: why with line: std::cout << ""; code does work, and without this line code doesn't work? How it is possible that printing some text on screen, can affect on how program works? It is a matter of some buffering or smth. like this?


#include <iostream>

int NWD(int a, int b){
    int r;
    while (r != 0){
        if (a>b)
            r = a-b;
        else
            r = b-a;
        a = b;
        b = r;
    }
    return a;
}

int NWW(int a, int b){
    std::cout << "";  // without this code doesn't work
    return a*b/ (NWD(a,b));
}

int NWW3(int a, int b, int c){
    return NWW(c, NWW(a,b));
}

int main()
{
    cout << NWW3(1,7,9);
}

CodePudding user response:

In your NWD() function:

int NWD(int a, int b){
    int r; <-- notice this
    while (r != 0){
        if (a>b)
            r = a-b;
        else
            r = b-a;
        a = b;
        b = r;
    }
    return a;
}

You declare r, but you didn't assign any value to r, so r is now uninitialized.

Then, you compare r with 0 in r != 0. Because r is uninitialized, this cause undefined behaviour. Undefined behaviour can do anything, from still running normally to crashing the program.

A quick fix to this problem is to initialize r with a non-zero value:

int r {-1}; 

Another issue is in main():

int main()
{
    cout << NWW3(1,7,9);
}

It should be:

int main()
{
    std::cout << NWW3(1,7,9);
}

CodePudding user response:

In your main function, you have cout declared, but have not included the standard namespace along with it, like you have done on in your NWW function.

So it should look like

int main()
{
    std::cout << NWW3(1,7,9);
}

You could also include " using namespace std; " under the header files.

This fills in the std:: for you as it pulls cout from its list of predefined features.

  •  Tags:  
  • c
  • Related