[問題] C++簡單的陣列題目

作者: WuluJason (五路皆神)   2018-05-22 12:58:09
開發平台(Platform): (Ex: Win10, Linux, ...)
win 10
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Dev C++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
我是高中生,因為興趣所以自學程式語言C++,配合學校的資訊課練習code,這次的作業是
輸入0-9的20個整數並計算各有幾個 初步的想法自己覺得有點笨拙...
我的想法如下
(抱歉這用手機打的 晚點用電腦編輯
這看起來是有點笨拙的寫法 但請求指正或是更好的寫法
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
#include <iostream>
using namespace std;
int main() {
int i , a[20];
cout<<"請輸入20個0-9的數字:;
int b=0,c=0,d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0;
for ( i=0 ; i<20 ; i++) {
cin>>a[i];
if (a[i]==1) b++;
if (a[i]==2) c++;
if (a[i]==3) d++;
if (a[i]==4) e++;
if (a[i]==5) f++;
if (a[i]==6) g++;
if (a[i]==7) h++;
if (a[i]==8) j++;
if (a[i]==9) k++;
if (a[i]==0) l++;
}
cout<<"1:"<<b<<"\t";
cout<<"2:"<<c<<"\t";
cout<<"3:"<<d<<"\t";
cout<<"4:"<<e<<"\t";
cout<<"5:"<<f<<"\t";
cout<<"6:"<<g<<"\t";
cout<<"7:"<<h<<"\t";
cout<<"8:"<<j<<"\t";
cout<<"9:"<<k<<"\t";
cout<<"0:"<<l<<"\t";
return 0;
}
作者: jerryh001   2018-05-22 13:03:00
1.變數命名要有規則 2.把"數有幾個"的變數做成陣列 3.重複的部分用迴圈做
作者: longlongint (華哥爾)   2018-05-22 13:05:00
count[a[i]]++
作者: bluesoul (忙死你老爸)   2018-05-22 13:06:00
記得先檢查輸入是否介於零到九
作者: achicn3 (Sher)   2018-05-22 15:13:00
Counting sort
作者: Royne (哲哉)   2018-05-22 18:03:00
矩陣a[10]初始值為0 每次cin>>i a[i]++
作者: remember (人老也有天使收)   2018-05-23 20:03:00
STL 的 map XD
作者: bhbbbbb (影)   2018-05-24 16:57:00
應該再多令一個array放你的abcdefg,你的一大串if還有最後輸出用for迴圈跑就ok了for(int j = 0 ; j < 10 ; j++) if(a[i] == j) b[j] ++ ;類似這樣,array記得先全部初始化成0

Links booklink

Contact Us: admin [ a t ] ucptt.com