C++程式編寫

2008-08-05 5:04 am
Reversing Digits

In this lab you are going to write a recursive function, reverseDigits, which takes a positive integer as a parameter and returns the number with the digits reversed.

e.g.: if the argument is 1234 then the returned value of reverseDigits will be 4321; if the argument is 500 then the returned value will be 5.

下面係skeleton
#include <iostream>
using namespace std;
int reverseDigits(____________);

int main(){
int num;
cout << "Enter a number: ";
cin >> num;
cout << "The reversed number: " << reverseDigits(____________) << endl;

return 0;
}

int reverseDigits(________________)
{
/*** Your Code ***/


}

請懂得者回答,在your code到寫就得

回答 (2)

2008-08-05 11:31 pm
✔ 最佳答案
how about the result if enter 10203040?
is 4030201
or 4321?

2008-08-05 15:31:37 補充:
#include <iostream>

using namespace std;
int reverseDigits( int );

int main(){
int num;
cout << "Enter a number: ";
cin >> num;
cout << "The reversed number: " << reverseDigits( num ) << endl;

return 0;
}

int reverseDigits( int inum )
{
int numr = 0, x = 0;

for ( x = 0; inum > 0; x++ )
{
( numr *=10 ) += inum % 10;
inum /= 10;
}

return numr;
}



OK?



2008-08-05 16:07:49 補充:
sorry. the variable "x" in function reverseDigits can be ignore. pls change the function to following code.

int reverseDigits( int inum )
{ int numr = 0;

for ( ; inum > 0; )
{ ( numr *=10 ) += inum % 10;
inum /= 10;
}

return numr;
}
2008-08-06 2:20 am
thx


收錄日期: 2021-04-13 15:54:51
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080804000051KK03080

檢視 Wayback Machine 備份