I need to write a C++ code that take an input number, divide that number by 2, print out the result, divide that result by 2, print out the new result, ...keep doing it until the newest result = 1, print that out also. Like this:
100 = input
Print out:
100
50
25
12.5
6.25
....
1
Does anyone have a hint on how to write this code?
No. Don't just throw out random guesses, but rather educate yourself and look up what a for loop consists of.
And although a for loop would work fine in this case, you might be better off with a while loop.
So with that in mind, does it make sense for the condition to be i<=number for what you want to achieve?
You should halve and print your current value until it is equal to 1.
Well, you can do it that way if you want. But xor is something entirely different from a power.
Use pow(2.0,i) to calculate 2^i (you need to include <cmath>).
I've done it !!
Thank you for your hints: pow(2.0,i), and <cmath>
Here is my code:
int half(double number)
{
cout << "This is a half-number program.\n";
cout << "Number must be 1 or greater.\n";
cout << "Enter a number: ";
cin >> number;
cout << "Number = " << number << ".\n";
double result;
for (int i = 0; i <= number; i++)
{
result = number / pow(2.0,i);
if (result < 1)
{
cout << "1.\n";
break;
}
cout << result << ".\n";
}
}
The condition still doesn't really make sense, you should omit it completely. Also, consider what happens when you enter a power of two (like 2 or 128).
Aside from that, good job.
somehow it makes sense to me.
i want to sent you my cpp code, but i don't know how to do it here.
so i copy all my code & put it here so you can try it out.
-----------
#include <iostream>
#include <cmath>
#include <stdio.h>
using namespace std;
int say_hello(int number);
int product(int x, int y);
int half(double number);
int main()
{
for ( ; ; )
{
int number;
say_hello(number);
int x, y;
product(x, y);
half(number);
}
getchar();
return 0;
}
int say_hello(int number)
{
cout << "Hello.\n";
cout << "Enter a number: ";
cin >> number;
for (int i = 1; i <= number; i++)
{
cout << "Hello.\n";
}
}
int product(int x, int y)
{
cout << "This is a multiplication calculation.\n";
cout << "Enter first number: ";
cin >> x;
cout << "Enter second number: ";
cin >> y;
cout << "The product of " << x << " and " << y << " = " << (x * y) << ".\n";
}
int half(double number)
{
do
{
cout << "This is a half-number program.\n";
cout << "Number must be 1 or greater.\n";
cout << "Enter a number: ";
cin >> number;
}
while (number < 1);
cout << "Number = " << number << ".\n";
double result;
for (int i = 0; i <= number; i++)
{
result = number / pow(2.0,i);
if (result <= 1)
{
cout << "1.\n";
break;
}
cout << result << ".\n";
}
}
-------------