//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; }