我在使用汽车的结构实现时遇到问题,我需要在车库输出每辆车的数量,所以在我的情况下输出应该是: 奥迪3 福特1 保时捷1 我是堆栈的唯一元素的计数,我知道有必要创建字符串数组,并通过我的结构,并在每次当到达结束时添加新元素,并且在数组中找不到元素字符串。
#include <stdio.h>
#include <Windows.h>
#include <time.h>
typedef struct Auto{
char Model [16];
char Number [8];
char Color [10];
char Name [16];
};
int main() {
int i, j, counter = 0;
char EnteredModel[16] = { "Audi" };
struct Auto MyAuto[5] = { { "Audi", "x007x", "blue", "Alexander" },
{ "Ford", "x777x", "red", "Andrey" },
{ "Porsche","a000b", "white", "Oleg"},
{ "Audi", "x007x", "blue", "Sergey"},
{ "Audi", "f666f", "black", "Daniel"} };
//printf("Enter the number of the interested model: ");
//scanf("%s", &EnteredModel);
for (i = 0; i < 5; i++) {
if (i == 0) {
printf("#####################################################\n");
printf("#Model #Number #Color #Name #\n");
printf("#####################################################\n");
}
if (strcmp(MyAuto[i].Model, EnteredModel)) {
printf("%-17s%-9s%-11s%-17s\n", MyAuto[i].Model, MyAuto[i].Number, MyAuto[i].Color, MyAuto[i].Name);
}
}
for (j = 0; j < 5; j++) {
for (i = 0; i < 5; i++) {
if (strcmp(MyAuto[i].Model, MyAuto[j].Model) == 0) {
counter++;
}
}
printf("%s = %d\n", MyAuto[j].Model, counter);
counter = 0;
}
printf("\n");
system("pause");
return 0;
}
答案 0 :(得分:0)
一种方法是制作一个“模型计数”数组,其长度与当前数组相同,并用它来“记住”你已经计算过的汽车。
示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Auto{
char Model [16];
char Number [8];
char Color [10];
char Name [16];
};
int main() {
int i, j, counter=0;
char EnteredModel[16] = { "Audi" };
struct Auto MyAuto[5] = { { "Audi", "x007x", "blue", "Alexander" },
{ "Ford", "x777x", "red", "Andrey" },
{ "Porsche","a000b", "white", "Oleg"},
{ "Audi", "x007x", "blue", "Sergey"},
{ "Audi", "f666f", "black", "Daniel"} };
int modelCounted[5] = {0};
//printf("Enter the number of the interested model: ");
//scanf("%s", &EnteredModel);
for (i = 0; i < 5; i++) {
if (i == 0) {
printf("#####################################################\n");
printf("#Model #Number #Color #Name #\n");
printf("#####################################################\n");
}
if (strcmp(MyAuto[i].Model, EnteredModel) == 0) {
// NOTICE: ^^^^
printf("%-17s%-9s%-11s%-17s\n", MyAuto[i].Model, MyAuto[i].Number, MyAuto[i].Color, MyAuto[i].Name);
}
}
printf("\n");
for (j = 0; j < 5; j++) {
if (!modelCounted[j]) // Only enter inner-loop if car hasn't been counted already
{
for (i = 0; i < 5; i++) {
if (strcmp(MyAuto[i].Model, MyAuto[j].Model) == 0) {
counter++;
modelCounted[i] = 1; // Mark car as counted
}
}
printf("%s = %d\n", MyAuto[j].Model, counter);
counter = 0;
}
}
printf("\n");
return 0;
}
输出:
#####################################################
#Model #Number #Color #Name #
#####################################################
Audi x007x blue Alexander
Audi x007x blue Sergey
Audi f666f black Daniel
Audi = 3
Ford = 1
Porsche = 1
BTW:注意第一个strcmp