//Requires: n >= 0
//Modifies: nothing
//Effects: returns the int formed by reversing the digits of n
// a parameter of 123 will return 321
// a parameter of 1234 will return 4321
// a parameter of 1230 will return 321 (or 0321)
// NOTE: 0321 will print as 321
int reverseNumber(int n)
{
{
int a = 1;
int b = 1;
int y = 1;
int x = 0;
while(b != 0)
{
a = n % 10;
x = x * 10 + a;
b = n / 10;
n = b;
}
return x;
}
}
and
1 2 3 4 5 6 7 8 9 10
//Requires: n >= 0;
//Modifies: n
//Effects: alters n to be the integer formed by reversing its digits
// if n = 123, then it will be altered to be 321
// if n = 1230, then it will be altered to be 0321, i.e., 321
void reverseNum(int &n)
{
reverseNumber(n);
}
Now this is my issue:
1 2 3 4 5 6
int main ()
{
int n = reverseNum(12);
cout << n;
}
The 12 has a red underline and won't compile. Compiler says 1>i:\project3\project3\test1.cpp(16): error C2664: 'reverseNum' : cannot convert parameter 1 from 'int' to 'int &'
And the red underline says "initial value of reference to non-const must be lvalue"
I'm pretty sure it's because you're passing a constant as a reference. Obviously you can't change the value of the number 12 (at least easily anyhow xD). Try this first:
1 2 3 4 5 6
int main () {
int n = 12;
int a = reverseNum(n);
cout << a;
return 0;
}
That won't work either because the reverseNum function is void.
1 2 3 4 5 6 7 8 9
//Requires: n >= 0;
//Modifies: n
//Effects: alters n to be the integer formed by reversing its digits
// if n = 123, then it will be altered to be 321
// if n = 1230, then it will be altered to be 0321, i.e., 321
void reverseNum(int &n)
{
reverseNumber(n);
}
And we can't change that.
When I did
1 2 3 4 5 6 7
int main ()
{
int n = 12;
reverseNum(n);
cout << n;
return 0;
}
int main ()
{
int n = 12;
reverseNum(n);
cout << n;
return 0;
}
Note that n will still remain unchanged because all you're doing is passing it into reverseNumber by value. You will have to modify reverseNum (or reverseNumber) for n to change.
//Requires: n >= 0;
//Modifies: n
//Effects: alters n to be the integer formed by reversing its digits
// if n = 123, then it will be altered to be 321
// if n = 1230, then it will be altered to be 0321, i.e., 321
void reverseNum(int &n)
{
reverseNumber(n);
}
For n to change? I am even more confused now. The reverseNumber function works 100%, it has passed in my autograder. But reverseNum just gives back the number without it being reversed.
void reverseNum(int &n)
{
//assigning the value of n to that returned from reverseNumber
//n will be passed in by value (so it won't change by parameter passing)
//however, we modify it with the assignment.
n = reverseNumber(n);
}