【发布时间】:2018-04-17 22:12:50
【问题描述】:
我的 CIS 课程有一个编码作业。任务是编写一个程序,该程序将创建一个结构数组,该数组将保存最多 10 只狗的信息。在程序结束时,您应该按名称或大小对狗的数组进行排序。但是我无法对狗数组的排序进行编码。
我想知道如何对狗数组进行排序以供以后在主函数中使用。
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Dog{
char name[20];
int weight;
int age;
int ageDogYears;
char size[7];
};
typedef struct Dog DG;
void calc(DG[], int);
void sort(DG[], int);
void display();
int main(){
DG dArray[10];
int x = 0;
char str[80], *i;
FILE *inFile;
inFile = fopen("dogfile.txt", "r");
if (inFile == NULL){
printf("Error opening file");
exit(1);
}
while(fgets(str, 80,inFile) != NULL){
i = strtok(str, ", ");
strcpy(dArray[x].name, i);
puts(dArray[x].name);
i = strtok(NULL, ", ");
dArray[x].weight = atoi(i);
printf("%d\n", dArray[x].weight);
i = strtok(NULL, ", ");
dArray[x].age = atoi(i);
printf("%d\n", dArray[x].age);
x++;
}
calc(dArray, x);
sort(dArray, x);
return 0;
}
void calc(DG dog[], int numDogs){
int y, i, total;
for(i = 0; i < numDogs; ++i){
if(dog[i].weight <= 20){
//sets the dog size to small
strcpy(dog[i].size, "Small");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 15;
else if(y == 1)
total += 8;
else if(y == 2)
total += 5;
else
total += 4;
}
}
else if(dog[i].weight <= 50){
//sets the dog size to medium
strcpy(dog[i].size, "Medium");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 14;
else if(y == 1)
total += 9;
else if(y == 2)
total += 7;
else
total += 5;
}
}
else{
//sets the dog size to Large
strcpy(dog[i].size, "Large");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 12;
else if(y == 1)
total += 9;
else if(y == 2)
total += 8;
else
total += 7;
}
}
dog[i].ageDogYears = total;
total = 0;
}
}
void sort(DG dog[], int numDogs){
int sortType, i, y, temp;
printf("\n wlould you like to sort by name(N) or size(S): ");
scanf("%c", &sortType);
switch(sortType){
case 'N': case 'n':
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs); ++y){
if(dog[y].weight > dog[y+1].weight){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
break;
default:
if((sortType != 's') && (sortType != 'S'))
printf("\n invalid input! Setting sort type to size.");
//sorting of dog names
}
}
示例输入
Fluffy,23,6
Fido,65,7
Pepper,44,5
Bowser,75,10
Victor,10,2
Sassy,51,1
任何帮助将不胜感激!谢谢。
【问题讨论】:
-
if(dog[y].weight > dog[y].weight){我想你这里有一个错字。您正在将同一只狗与自己进行比较(两个指数都是y)。你想写什么样的类型?另外,请注意您的数组范围。 -
感谢您的反馈,是的,我确实在该行中发现了一个错字。该行应为
if(dog[y].weight > dog[y+1].weight){。但根据我对冒泡排序的研究,它仍然应该是y。 -
请向我们提供一个示例输入并将整个代码编写在一个块中。此外,我们无法访问
calc函数,只能访问原型。 -
temp是一个int,而dog[y]是一个结构,所以temp = dog[y]应该会给你一个错误。 -
再次检查您的索引。
标签: c arrays sorting struct bubble-sort