我試圖交換兩個陣列位置的內容,其中陣列是一個結構的陣列。 我的代碼是:
#include <stdio.h>
#include <Conio.h>
#include <stdlib.h>
struct Student
{
char name[800] 。
int roll;
double phys, chem, maths,sum;
};
typedef struct Student Student; /span>
void main()
{
學生 *st,temp;
int n,i,j;
printf("輸入學生的數量。
")。)
scanf("%d"/span>,&n)。
st = (Student *)malloc(n*sizeof(學生))。
printf("輸入每個學生的詳細資料。
")。)
for(i=0; i<n; i )
{
scanf(" %s %d %lf %lf",&st[i].name,&st[i].roll,&st[i].phys,&st[i].chemical,&st[i].maths) 。
st[i].sum = st[i].phys st[i].chem st[i].maths。
}
for(i=0;i<(n-1); i )
{
for(j=0;j< (n-i-1); j )
{
if(st[j].sum < st[j 1].sum) 。
{
temp = st[j];
st[j] = st[j 1]。
st[j 1] = temp;
}
}
}
printf("The list of student is :
")。)
for(i=0; i<n; i )
{
printf("%d %s
",st[i].roll,st[i].name)。
}
getch()。
}
但是這種交換并沒有發生。我已經用靜態結構陣列做了類似的交換,它是有效的,但這個交換卻沒有。我沒有產生任何錯誤,它的編譯完全正常。實際上,我正試圖根據降序進行交換。但輸出結果總是與輸入結果相反。誰能幫幫我?
uj5u.com熱心網友回復:
你的代碼中存在一個錯誤。在雙for回圈內,在if條件后,有;,這意味著你的if沒有在{}塊內保護陳述句。
洗掉這一點,它應該可以正常作業。請看下面代碼的第3行:
for(i=0;i<(n-1) ;i ) {
for(j=0;j< (n-i-1);j ) {
if(st[j].sum < st[j 1] .sum) {
temp = st[j];
st[j] = st[j 1]。
st[j 1] = temp;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/306925.html
標籤:
