程序在写入时给出错误答案,但在复制时给出正确答案

0 c

我正在做选择排序.我写的程序产生了错误的结果,但是当我从网站上复制它时.代码完全相同,只是从网站复制的代码有更多的空格.我提供这两个代码.请帮助我写的代码:

#include<stdio.h>
main()
{
int position, array[100], n, c, d, swap;
printf ("Enter the number of elements:\n");
scanf ("%d", &n);
printf ("Enter the %d integer\n",n);
for (c=0 ; c < n ; c++)
scanf ("%d", &array[c]);
for (c = 0 ; c < (n-1); c++)
{
position=c;
for (d = c+1; d < n; d++)
{
if (array[position] > array[d]);
position = d;
}
if (position !=c);
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf ("Sorted list in the ascending order:\n");
for (c=0 ; c < n ; c++)
printf ("%d\n", array[c]);
getch();
}
Run Code Online (Sandbox Code Playgroud)

网站上给出的代码

#include<stdio.h>

main()
{
   int array[100], n, c, d, position, swap;

   printf("Enter number of elements\n");
   scanf("%d", &n);

   printf("Enter %d integers\n", n);

   for ( c = 0 ; c < n ; c++ )
      scanf("%d", &array[c]);

   for ( c = 0 ; c < ( n - 1 ) ; c++ )
   {
      position = c;

      for ( d = c + 1 ; d < n ; d++ )
      {
         if ( array[position] > array[d] )
            position = d;
      }
      if ( position != c )
      {
         swap = array[c];
         array[c] = array[position];
         array[position] = swap;
      }
   }

   printf("Sorted list in ascending order:\n");

   for ( c = 0 ; c < n ; c++ )
      printf("%d\n", array[c]);

  getch();
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 10

它们不一样 - 你们有一个:

if (array[position] > array[d]);
position = d;
Run Code Online (Sandbox Code Playgroud)

而在另一个你有:

     if ( array[position] > array[d] )
        position = d;
Run Code Online (Sandbox Code Playgroud)

注意第一个中的分离分号,它完全改变了程序的语义.

请注意,在编译时应始终启用警告(例如gcc -Wall) - 这有助于捕获愚蠢但难以处理的错误,例如上面的示例.


编辑正如@Lucas所指出的那样,你似乎在程序的其他地方也犯了同样的错误,例如if (position !=c);- 注意C中的分号不仅仅是用于美容效果 - 分散的分号(或缺少分号)可以大大改变程序的行为.

  • 令人印象深刻 (3认同)