reversing float

Take floating point number from user and reverse it
For example user enter
123.45

Your program should reverse it
Output should be 54.321
with basic if else while....
Last edited on
closed account (48T7M4Gy)
Excellent challenge. We look forward to seeing your program, perhaps even pseudocode. My guess is your solution will incorporate <strings>'s
Basic if else while?
Can't you just do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
float ReverseFloat(string s)
{
	reverse(s.begin(), s.end());
	return stof(s);
}

int main()
{
	string strNum{};
	cin >> strNum;
	
	float number = ReverseFloat(strNum);

	return 0;
}


Well, maybe is an homework, so have fun :P
Last edited on
#include <iostream>
using namespace std;

int main()
{
float reversedNumber = 0.0, remainder;
float n;

cout << "Enter an integer: ";
cin >> n;

while(n != 0.0)
{
remainder = n%10.0;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}

cout << "Reversed Number = " << reversedNumber;

return 0;
}
why this one doesnt work
Please use code tags. http://www.cplusplus.com/articles/jEywvCM9/
You can edit your post, highlight your code and click the <> button on the right.

remainder = n%10.0;
operator% isn't defined for floating point numbers. You'll need to use fmod instead.

1
2
3
4
5
6
while(n != 0.0)
{
remainder = n%10.0;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}

This will become an infinite geometric progression, but will eventually end due to the finite precision of float/double. For example, take n = 12.34, just dividing n by 10.
1
2
3
4
5
6
7
12.34
1.234
0.1234
0.01234
0.001234
0.0001234
... etc


As suggested above, convert the float to a string(stringstream or to_string) and reverse that string(reverse or rbegin/rend).
Topic archived. No new replies allowed.