C++ while loop?

2016-04-30 3:32 pm
This program reverses digits of a number for eg 125 will be reversed to 521 but i dont get the while loop can anyone explain me how while loop is working here


#include <iostream>
using namespace std;

int reverseDigit(int num)
{
int result = 0;
bool isNegative=false;

if(num<0)
{
isNegative=true;
num*=-1;
}

while(num > 0) \\ please explain this loop
{
result = result*10 + num%10;
num /= 10;
}

if (isNegative)
{
result*=-1;
}

return result;
}

int main()
{
bool isNegative=false;
int amount;
cout<<"Enter the number to be reversed : ";
cin>>amount;
cout<< endl;
cout<<"The number reversed is : ";
cout << reverseDigit(amount) << endl;
}

回答 (3)

2016-04-30 4:01 pm
✔ 最佳答案
Suppose the number is 125:
The variables that are of interest are 'result' and 'num' which are equal to 0 and 125, respectively.
In the first iteration of the loop: is num>0 -> YES; result = 0*10 + 125%10 = 0+5 = 5; num = 125/10 = 12;
In the second iteration of the loop: is num>0 -> YES; result = 5*10 + 12%10 = 50 + 2 = 52; num = 12/10 = 1;
In the third iteration of the loop: is num>0 -> YES; result = 52*10 + 1%10 = 520 + 1 = 521; num = 1/10 = 0;
In the fourth iteration of the loop: is num>0 -> NO -> end loop

So basically, the loop is reversing the digits of the number.
2016-04-30 9:21 pm
Basically it makes the loop execute once for every digit in the original number.
102 would execute 3 times, 78904, 5 times etc.
It just keeps dividing by ten until it reaches zero.
2016-04-30 6:47 pm
int main()
{ // you are not using isNegative in this function.
int amount;
cout<<"Enter the number to be reversed : ";
cin>>amount;
// no need for endl here you already pushed return
cout<<"The number reversed is : ";
cout << reverseDigit(amount) << endl;
return 0; // better style
}


收錄日期: 2021-04-21 18:25:17
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20160430073209AAS0ctr

檢視 Wayback Machine 備份