注册 登录
编程论坛 C++教室

剖析整数反序输出~~~~~帮忙 注释下了。。。。

七夜之华 发布于 2014-11-28 15:07, 699 次点击
/*#include<iostream>// . 编写一个程序,要求输入一个整数,将各位数字反序后输出。
using namespace std;
int main(){
    int x,ox;
    int bw,sw,gw;
    cout<<"请输入一个整数:"<<endl;
    cin>>x;
    bw=x%100;                                
    sw=x%10;
    gw=x%1;
    ox=gw*100+sw*10+bw*1;
    cout<<"取反后数字为:"<<ox<<endl;
    system("pause");
    return 0;
}
 */   
   

#include<iostream>
using namespace std;
int main()
{
   int n,right_digit,newnum=0;
   cout<<"请输入整数值:"<<endl;
   cin>>n;
   cout<<"反序输出数据为:"<<endl;
   do
   {
      right_digit=n%10;
      newnum=newnum*10+right_digit;
      n/=10;
   }while (n);
   cout<<newnum<<endl;
   system("PAUSE");
   return 0;
}
5 回复
#2
rjsp2014-11-28 15:37
这小学三年级就能解决的数学问题还要注释?
另外,你的代码,变量定义到头部,即使在现在的C标准中,也明确写着“摒弃”这么做。我帮你改一下
程序代码:
#include <iostream>
using namespace std;

int main()
{
    unsigned n;
    cin >> n;

    unsigned long long m = 0;
    for( ; n; n/=10 )
        m = m*10 + n%10;
    cout << m << endl;

    return 0;
}
之所以用 unsigned long long,是因为 反序 后,unsigned int 未必能装得下,比如 1111111119

你的题目要求中只需要输出,那就不必考虑溢出的问题了
程序代码:
#include <iostream>
using namespace std;

int main()
{
    unsigned n;
    cin >> n;

    if( n == 0 )
    {
        cout << 0;
    }
    else
    {
        for( ; n%10==0; n/=10 );
        for( ; n; n/=10 )
            cout << n%10;
    }
    cout << endl;

    return 0;
}

#3
七夜之华2014-11-29 09:27
只有本站会员才能查看附件,请 登录
  解释下这里的第一个for后面的  ;代表的意思。、、、、、
                        加 ;运行的结果正确,不加;的话运行就没有结果





###################################################
##################################################
 因为不懂、才要学习,因为学习、才有进步。
#4
小码农2014-11-29 19:29
回复 2 楼 rjsp
版主的第一个for循环没弄懂,可以讲解下吗。

[ 本帖最后由 小码农 于 2014-11-29 19:31 编辑 ]
#5
rjsp2014-12-01 08:42
第一个for是为了去掉后缀的0
比如 123000000
如果反序的话为 000000321
而去掉后缀的0再反序的话为 321
#6
小码农2014-12-01 13:03
回复 5 楼 rjsp
奥,明白了
1