作者genhao6729 (蝦咪挖溝)
看板C_and_CPP
標題[問題] 有關c++的switch應用
時間Tue Mar 30 02:14:29 2010
使用結構體存取位元的方式來控制是否使用Bubblesort進行排序(需由輸入控制)
我寫的程式如下
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct student
{
char stu_id[12];
int ScoreComputer;
int ScoreMath;
int ScoreEng;
float ScoreAvg;
};
void display(struct student);
void BubbleSort(struct student *arr,int arr_index);
void display(struct student tempStu)
{
cout << tempStu.stu_id << "\t" << tempStu.ScoreComputer << "\t" \
<< tempStu.ScoreMath << "\t" << tempStu.ScoreEng << "\t";
cout << setprecision(4) << tempStu.ScoreAvg << endl;
}
void BubbleSort(struct student *arr,int arr_index)
{
int k,times,i;
struct student temp;
k=arr_index-1;
while(k!=0)
{
times=0;
for(i=0;i<=k+1;i++)
{
if(arr[i].ScoreEng>arr[i-1].ScoreEng)
{
temp=arr[i]; arr[i]=arr[i-1]; arr[i-1]=temp; // arr[i]與arr[i+1]互換
times=i;
}
}
k=times;
}
}
struct flag
{
unsigned short int f1:1;
};
int main(void)
{
int score[3][3]={{89,84,75},
{77,69,87},
{65,68,77}};
struct student IM[3];
int i,Total;
strcpy(IM[0].stu_id,"S9103501");
strcpy(IM[1].stu_id,"S9103502");
strcpy(IM[2].stu_id,"S9103503");
for(i=0;i<3;i++)
{
Total=0;
IM[i].ScoreComputer=score[i][0];
IM[i].ScoreMath =score[i][1];
IM[i].ScoreEng =score[i][2];
Total=score[i][0]+score[i][1]+score[i][2];
IM[i].ScoreAvg=((float)Total)/3;
}
int a[2];
int h;
for(h=0;h<1;h++)
{
cout << "請輸入是否使用Bubblesort進行排序(否:0;是:1):" << endl;
cin >>*(a+h);
}
struct flag PSW;
switch(PSW.f1)
{
case 0:
cout << "學號\t\t計概\t數學\t英文\t平均" << endl;
cout << "------------------------------------------------" << endl;
for(i=0;i<3;i++)
display(IM[i]);
break;
case 1:
cout << "學號\t\t計概\t數學\t英文\t平均\t(依計概排序前)" << endl;
cout << "---------------------------------------------------" << endl;
for(i=0;i<3;i++)
display(IM[i]);
BubbleSort(IM,3);
cout << "學號\t\t計概\t數學\t英文\t平均\t(依計概排序後)" << endl;
cout << "---------------------------------------------------" << endl;
for(i=0;i<3;i++)
display(IM[i]);
break;
}
system("pause");
return 0;
}
不管我輸入0或者1
輸出的結果都是case 0的結果
不知道哪裡出問題說
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 203.217.104.26
推 legendmtg:你輸入給a[] 然後拿PSW.f1去switch? 03/30 02:32
→ genhao6729:那要怎麼把a[]改成PSW.f1 03/30 02:44
→ genhao6729:要用輸入控制不是就要矩陣去弄 03/30 02:45
推 LPH66:關鍵字: union 不過除非你是想練習這個位元存取 03/30 05:39
→ LPH66:不然這方法用在這裡實在用處不大... 03/30 05:39