在数组中打印数值未按预期工作。

huangapple go评论46阅读模式
英文:

Printing out values in an array not working as expected

问题

以下是你的代码的翻译部分:

我被分配了一个任务,根据给定的结构来输入学生信息,其中每个信息字段应该逐行输入,以空格分隔,然后按学生ID递增排序,然后打印出信息,每个学生占一行。问题是,尽管我认为我的代码很好,但打印部分一直给出了不完整的结果,总体来说,没有打印出正确的值。我应该在哪里修复这个问题?

以下是我的代码:

#include <stdio.h>;
typedef struct
{
    char id[8];
    int year;
} student;

int main() {
    student std[100];
    int i, j, num, tmp;
    printf("So sinh vien:\n");
    scanf("%d", &num);
    printf("Nhap thong tin sinh vien:\n");
    for (i = 0; i <= num; i++)
    {
        scanf("%c %d\n", &std[i].id, &std[i].year);
    }

    for (i = 0; i < num; i++)
    {
        for (j = 1; j < num; j++)
        {
            if (std[i].id > std[j].id)
            {
                tmp = *std[i].id;
                *std[i].id = *std[j].id;
                *std[j].id = tmp;
            }
        }
    }
    for (i = 0; i < num; i++)
    {
        printf("%c ", std[i].id);
        printf("%d\n", std[i].year);
    }
    return 0;
}

你的输出是:

So sinh vien:
3
Nhap thong tin sinh vien:
12324521 2003
12341552 2002
12357263 2001
Σ       12324521
≡       3
ⁿ       2341552

如果你的代码有问题,我建议你仔细检查以下几个方面:

  1. 循环边界:你的循环应该是 for(i=0; i<num; i++) 而不是 for(i=0; i<=num; i++)。最后一个循环也应该是 for (j = 1; j < num - i; j++)

  2. 学生ID的输入:学生ID应该作为字符串输入,而不是字符。所以应该使用 %s 而不是 %c

  3. 学生ID的排序:在排序学生ID时,你可以使用字符串比较而不是整数比较。

  4. 打印学生ID时,你可以使用 %s 而不是 %c

英文:

I was tasked with inputting student information based on a given struct, where each field of information is to be typed in one line, separated by a space, then the student id is sorted incrementally, and then print out the information, each student on a new line. The problem is while I thought my code was good, the print part keeps giving fractured results and overall just not printing out the correct values. Where should I fix this?

Here's my code:

#include &lt;stdio.h&gt;
typedef struct 
{
	char id[8];  
	int year; 
}student; 

int main() {    
	student std[100];
	int i, j, num, tmp;
    printf(&quot;So sinh vien:\n&quot;);
    scanf(&quot;%d&quot;, &amp;num);
    printf(&quot;Nhap thong tin sinh vien:\n&quot;);
for(i=0; i &lt;= num; i++)
	{
		scanf(&quot;%c %d\n&quot;, &amp;std[i].id, &amp;std[i].year);
	} 

for(i=0; i &lt; num; i++)
	{
		for (j=1; j&lt; num; j++)
		{
			if (std[i].id &gt; std[j].id)
            {
				tmp = *std[i].id
				*std[i].id = *std[j].id;
				*std[j].id = tmp;
			}
		}
	}
for(i=0; i &lt; num; i++)
	{
		printf(&quot;%c	&quot;, std[i].id);
		printf(&quot;%d\n&quot;, std[i].year);
	}
  return 0;
}

My output is

So sinh vien:
3
Nhap thong tin sinh vien:
12324521 2003
12341552 2002
12357263 2001
Σ       12324521
≡       3
ⁿ       2341552

答案1

得分: 1

  1. 检查 scanf() 的返回值,否则可能会操作未初始化的变量。

  2. 检查 num 是否小于为学生分配的 100 条记录,或者更好地使用可变长度数组 (VLA),并添加检查以避免大量输入导致堆栈溢出。

  3. 你输入 num,然后读取 num+1 条记录,但后来只打印了 num 条记录。

  4. 当你用 "%c" 读取字符时,第一个输入将是前一个 scanf() 的换行符 \n

  5. 结构体包含一个 char id[8],但你只读取一个字符到它。改为读取一个字符串。

  6. 在排序部分,你使用 > 来比较 ID 的第一个字母。你可能想要使用 strcmp() 来比较字符串。

  7. 在排序部分,你使用一个 int tmp 来存储 ID 的字符(这是可以的),但然后你写入一个整数,这是不正确的。

  8. 在排序部分,你只交换了 ID。你可能想要交换整个记录,而不仅仅是 ID。

  9. 这似乎是一种交换排序。使用一个函数,并且对我来说,算法似乎不起作用,因为内部循环变量应该从 j=i+1 开始,而不是 1

  10. 在你的打印函数中,将 char id[8] 作为字符串而不是单个字符。

  11. 将打印功能移到一个函数中。这允许你在调试期间在 sort() 之前和之后打印学生信息。

  12. 限制变量的作用域(ij 现在是循环局部变量,tmp 仅在 swap() 函数中使用)。这使得代码更容易理解。

英文:
  1. Check the return value of scanf() otherwise you may be operating on uninitialized variables.

  2. Check that num less than the 100 records you allocated for student, or even better use a vla along with a check to avoid large input from smashing the stack.

  3. You input num then read num+1 records but later you only print num records.

  4. As you read a character with "%c" the first input with be the \n from the previous scanf().

  5. The struct contains a char id[8] but you only read a single character into it. Read a string instead.

  6. In sort you use &gt; to compare the first letter of id. You probably want to use strcmp() to compare strings.

  7. In sort section you use a int tmp for storing a character of id (which is ok) but then you write an int which is no good.

  8. In sort you only swap the ids. You probably want to swap the entire record not just the ids.

  9. It seems to be an exchange sort. Use a function, and also at least for me the algorithm didn't work as the inner loop variable should start at j=i+1 not 1.

  10. In your print char id[8] as a single char instead of string.

  11. Moved print functionality to a function. This allows you, for instance, to print the students before and after the sort() during debugging.

  12. Minimizing scope of variables (i and j are now loop local, tmp is only used in the swap() function). This makes code easier to reason about.

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#define ID_LEN 7
#define str(s) str2(s)
#define str2(s) #s

typedef struct {
	char id[ID_LEN+1];
	int year;
} student;

void swap(student *a, student *b) {
	student tmp = *a;
	*a = *b;
	*b = tmp;
}

void print(size_t num, student std[num]) {
	for(size_t i=0; i &lt; num; i++)
		printf(&quot;%s  %d\n&quot;, std[i].id, std[i].year);
}

// exchange sort
void sort(size_t num, student std[num]) {
	for(size_t i=0; i &lt; num - 1; i++)
		for (size_t j=i+1; j &lt; num ; j++)
			if(strcmp(std[i].id, std[j].id) &gt; 0)
				swap(&amp;std[i], &amp;std[j]);
}

int main() {
	printf(&quot;So sinh vien:\n&quot;);
	size_t num;
	if(scanf(&quot;%zu&quot;, &amp;num) != 1) {
		printf(&quot;scanf() failed\n)&quot;);
		return 1;
	}
	if(num &gt; NUM_MAX) {
		printf(&quot;Too many students\n&quot;);
		return 1;
	}
	student std[num];

	printf(&quot;Nhap thong tin sinh vien:\n&quot;);
	for(size_t i=0; i &lt; num; i++)
		if(scanf(&quot;%&quot; str(ID_LEN) &quot;s %d&quot;, std[i].id, &amp;std[i].year) != 2) {
			printf(&quot;scanf() failed\n&quot;);
			return 1;
		}

	sort(num, std);
    print(num, std);
}

and here is an example run:

So sinh vien:
3
Nhap thong tin sinh vien:
aaa 1
zzz 2
bbb 3
aaa  1
bbb  3
zzz  2

答案2

得分: 0

应更改为:

printf("%s  ", std[i].id);

%c 表示一个单个字符。

英文:
printf(&quot;%c  &quot;, std[i].id);

should be

printf(&quot;%s  &quot;, std[i].id);

%c means a single char.

huangapple
  • 本文由 发表于 2023年2月16日 10:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定