![]() |
| ||
| reversing number problem. i have done a simple program, which i asked..(don't know how many days ago.) but i find that there is a problem.. if i give an input (for example) 1234 it shall reverse back 4321 (it does) when i key in 100, by right it should return 001, but it returned as 1. my question is how to make that two zeros in front visible. (is there any mistake(s) for my "this" program??) #include <iostream> using namespace std; long reverse(); int main() { long a; a = reverse(); cout << "The reversed number is " << a << endl; return 0; } long reverse() { long x, y, z = 0; cout << "Enter an integer to be reversed: "; cin >> x; while (x > 0){ y = x%10; x = x/10; z = 10 * z + y; } return z; } thank you.... |
| ||
| Re: reversing number problem. The trouble here is you are using integers to reverse the number. That works for most things, but the number '1' could be '01' or '001' or '0001' and so on and you use a generic integer printing routine. Two easy solutions I can think of here; one is to return how many digits the answer should be and make a string out of the result with leading zeroes (using sprintf(), say). the other is to do the reversal as a string of chars. Both will take a small investment of time. The string reversal favors using the reverse() algorithm, whereas the sprintf is more of a clever formatting trick. |
| ||
| Re: reversing number problem. You should declear the number as a string or to convert it as a string. In your way it treat it as an integer and takes off the zeros of the front which don't mean anything for the compiler. |
| ||
| Re: reversing number problem. hi kho, here you take input as a integer.The 001,00001,01,1 is same thing to the cout. If you want to see output as 001 then you take input in a string. thanking you..... Rishi |
| ||
| Re: reversing number problem. Quote:
#include <iostream.h> |
| ||
| Re: reversing number problem. I don't under stand the part with the remainder. What does this part do? Quote:
|
| ||
| Re: reversing number problem. r = no % 100; ================== no = 120; 120 % 100 = 20; 130 % 100 = 30; 100 % 100 = 0; I dont konw how to describle it in Eglish. |
| ||
| Re: reversing number problem. Quote:
Then the remainder is taken again and the next digit can be stored |
| ||
| Re: reversing number problem. This program gets very easy with the use if recursive function if the job is only to print the number in the reverse order.
|
| ||
| Re: reversing number problem. >This program gets very easy with the use if recursive >function if the job is only to print the number in the reverse order. So, was it worth resurrecting a three year old thread to post some bad code? |
| All times are GMT -4. The time now is 3:23 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC