This is related to the beginner exercise I found on this site regarding functions.
The question goes something like this:
Design a user defined function called half() which halves a number you enter and continues to half it as long as it is greater than one.
Example :
Enter a number : 50
25
12
6
3
1
( I Think my integer division is right.. it may not be though..)
Following is my code, my problem is that if I insert a number it just keeps displaying the number; it doesn't half it or anything. Can anyone offer me any tips? Thanks.
#include <iostream>
usingnamespace std;
int half(int);
int main()
{
cout << "Give me a number: ";
int number;
cin >> number;
half(number);
return 0;
}
int half(int r)
{
int x;
while (r > 1)
{
cout << r;
x = r / 2;
}
return x;
}
#include <iostream>
usingnamespace std;
int Half (int);
int main ()
{
int Number;
cout << "Give me a number." << endl;
cin >> Number;
Half (Number);
cin.sync ();
cout << "Press ENTER to end the program." << endl;
cin.get ();
return 0;
}
int Half (int R)
{
while (R > 1)
{
R /= 2;
cout << R << endl;
}
return R;
}
@nadeem55555 Why are int functions bad (Sorry I am still new)?
@nadeem55555 Why are int functions bad (Sorry I am still new)?
I don't he's saying that it's bad. It's just pointless because the "Half" function prints to the standard output anyway, and the main function does not even use the return value.
Hey thank you for the help everyone. I have one more question, I am doing another exercise and it reads as follows :
1. Write a program that repeatedly asks the user to enter pairs of numbers until at least one
of the pair is 0. For each pair, the program should use a function to calculate the harmonic
mean of the numbers. The function should return the answer to main(), which
should report the result. The harmonic mean of the numbers is the inverse of the average
of the inverses and can be calculated as follows:
harmonic mean = 2.0 × x × y / (x + y)
My code works but it doesn't exit if one of the numbers is 0, can anyone help me out again(sorry for being a leech )
vince1027's solution makes sense in this case (assuming you only need to handle positive inputs?)
Otherwise you'll need to code a little comparsion function which tests the absolute difference between the number the test value is less than some small "delta".
Thank you very mcuh andy & vince, I used vince's solution since the exercise is not explicit and I'm trying not to overload myself with unnecessary extra stuff whilst I try to grasp the basics.