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

刚学C++。请人帮改个程序

haosw86 发布于 2008-11-07 16:16, 1042 次点击
题目是:要求输入一个不多于5位的正整数,要求输出:1求出是几位数,2分别输出各位上的数字,3按逆序输出该数,例如123,输出321。
下面是我自己写的,做错了~谁能给改下,或写个给我,谢谢了
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int s,i,j;
    int m=0;
    cout<<"please enter the number"<<'\n';
    cin>>s;
    while(s>99999||s<0)
    {
        cout<<"data error,enter again";
        cin>>s;
    }
    cout<<"各位数字分别是:";
    for (i=1;(i<5)&&((s/10)!=0);)
    {
        j=s%10;
        cout<<j<<",";    
        s=s/10;
        m=m+10*exp(i-1)*j; i++;
    }
    if((s/10)==0) cout<<s;
    cout<<"逆序数是:"<<m<<'\n'<<"位数是:"<<i<<endl;
    return 0;
}
7 回复
#2
mbstorm2008-11-07 16:33
while(s>99999||s<0)
s定义为int型不对,int型范围是-32768-32767
#3
haosw862008-11-07 16:53
我改成 long int后也不对,具体是那个m,我没考虑好怎么设置
#4
mbstorm2008-11-07 17:03
m=m+10*exp(i-1)*j; i++;

这里的exp不是自然对数的几次方吗
#5
zqm02092008-11-07 19:50
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int s,i,j;
    long int m=0;
    cout<<"please enter the number"<<'\n';
    cin>>s;
    while(s>99999||s<0)
    {
        cout<<"data error,enter again";
        cin>>s;
    }
    cout<<"各位数字分别是:";
    for (i=1;(i<=5)&&((s%10)!=0);i++)
    {
        j=s%10;
        cout<<j<<",";
        s=s/10;
        m=j+10*m;//逆序
}
   // if((s/10)==0) cout<<s;
    cout<<"逆序数是:"<<m<<'\n'<<"位数是:"<<(--i)<<endl;

    return 0;
}
直接在你程序基础上改的 ,你m那句用错了函数,应该写成 m=m+pow(10,i-1)*j;不过那样得到的是正序数,给你改过来了
#6
mbstorm2008-11-07 22:10
这样些太复杂了,请看:
#include <iostream>

using namespace std;
int main()
{
    int i,j,k;

       cout<<"请输入一个非负数:";
       cin>>i;
    
    cout<<i<<"的逆序数为";
    for(k=0;(k<5)&&(i>0);)
    {
        j=i%10;
            cout<<j;
        i=i/10; k++;
    }
    cout<<"数的位数为:"<<k;
    return 0;
}
#7
安徽U阿朱2008-11-07 23:50
回复 6# 的帖子
正  解!
#8
hitcolder2008-11-08 12:47
[bo][un]mbstorm[/un] 在 2008-11-7 22:10 的发言:[/bo]  

这样些太复杂了,请看:
#include

using namespace std;
int main()
{
    int i,j,k;

       couti;
    
    cout
经典,太简练了!!!
1