首页 > 代码库 > 41.用c++编写程序:从键盘上任意输20个1-99之间的整数,分别统计其个位数0-9的数字各有多少

41.用c++编写程序:从键盘上任意输20个1-99之间的整数,分别统计其个位数0-9的数字各有多少

//1、输入数字需要保存在数组中,注意数组的首元素问题
//2、需要截取出各位数字
//3、判断是哪一个数字
//4、进行计数

(1)我出错的程序:

#include<iostream>using namespace std;int main(){    int p[20];    int temp;    int a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0;    cout<<"please input 20 numbers between 1~99: "<<endl;    for(int i=0;i<10;i++)    {        cin>>p[i];    }    for(int j=0;j<10;j++)    {        temp=p[j]%10;        switch(temp)        {            case 1: a++;            case 2: b++;            case 3: c++;            case 4: d++;            case 5: e++;            case 6: f++;            case 7: g++;            case 8: h++;            case 9: i++;            case 0: j++;        }    }    cout<<"有9 "<<i<<""<<endl;    cout<<"有8 "<<h<<""<<endl;    cout<<"有7 "<<g<<""<<endl;    cout<<"有6 "<<f<<""<<endl;    cout<<"有5 "<<e<<""<<endl;    cout<<"有4 "<<d<<""<<endl;    cout<<"有3 "<<c<<""<<endl;    cout<<"有2 "<<b<<""<<endl;    cout<<"有1 "<<a<<""<<endl;    cout<<"有0 "<<j<<""<<endl;    return 0;}

(2)改正后的正确程序

#include<iostream>using namespace std;int main(){    int p[20];    int temp;    int a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,m=0,n=0;    cout<<"please input 20 numbers between 1~99: "<<endl;    for(int i=0;i<10;i++)    {        cin>>p[i];    }    for(int j=0;j<10;j++)    {        temp=p[j]%10;        switch(temp)        {            case 1: a++;break;            case 2: b++;break;            case 3: c++;break;            case 4: d++;break;            case 5: e++;break;            case 6: f++;break;            case 7: g++;break;            case 8: h++;break;            case 9: m++;break;//注意之前只用的for循环中已经有i,i了,不要重复            case 0: n++;break;//注意switch语句中的break和default不要忘记            default : break;        }    }    cout<<"有9 "<<m<<""<<endl;    cout<<"有8 "<<h<<""<<endl;    cout<<"有7 "<<g<<""<<endl;    cout<<"有6 "<<f<<""<<endl;    cout<<"有5 "<<e<<""<<endl;    cout<<"有4 "<<d<<""<<endl;    cout<<"有3 "<<c<<""<<endl;    cout<<"有2 "<<b<<""<<endl;    cout<<"有1 "<<a<<""<<endl;    cout<<"有0 "<<n<<""<<endl;    return 0;}