#include <iostream>
using namespace std;
int main()
{
int n,sum=0;
cout<<"enter no.";
cin>>n;
while(n!=0)
{
int r=n%10;
int sum= (sum*10)+r;
n=n/10;
}
cout<<sum;
return 0;
}
这里的输出应该反转一个数字,但它的o / p为'0'不懂你!!请帮助。
您的代码基本上是正确的,但是您在while循环中犯了一个小错误。旧代码:-
#include <iostream>
using namespace std;
int main()
{
int n,sum=0;
cout<<"enter no.";
cin>>n;
while(n!=0)
{
int r=n%10; //-- Y R U declaring the variables 'r' and 'sum' here?
int sum= (sum*10)+r;//-- Declare them at top and initialize 'sum' with 0
n=n/10;
}
cout<<sum;
return 0;
}
新代码:-
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter a number >> ";
cin >> n;
while (n != 0) {
sum = (sum * 10) + n % 10;
n /= 10;
}
cout << sum << endl;
return EXIT_SUCCESS;
}
输出:-
Enter a number >> 123456
654321
Press any key to continue . . . _
不读数字,不读字符串:
#include <iostream>
using namespace std;
int main()
{
std::string n;
cout<<"enter no.";
cin>>n;
std::string reversed(n.rbegin(), n.rend());
cout<<reversed;
return 0;
}
问题是int
之前的sum
在循环内部创建了一个隐藏外部sum
的局部变量。如果删除它,则程序将运行。您可能想在scoping中查找C ++变量。
#include <iostream>
using namespace std;
int main()
{
int n,sum=0;
cout<<"enter no.";
cin>>n;
while(n!=0)
{
int r = n % 10;
sum = (sum * 10) + r;
//^^ note no int
n=n/10;
}
cout<<sum;
return 0;
}