输出平均数时,程序出现分割错误11

时间:2018-11-24 12:14:08

标签: c scanf

这两组代码似乎彼此没有什么不同,但是其中一组会生成警告和分段错误11。

    //the program which turns out alright
    #include<stdio.h>
    int main()
    {int a,b,c,d;float f;
     scanf("%d %d %d",&a,&b,&c);
     d=a+b+c;
     f=(a+b+c)*1.0/3.0;
     printf("%d %.2f\n",d,f);
     return 0;
     }

   //the program that comes along small issues
   //format specifies type 'int *' but the argument has type 'int' [-Wformat]
   //After inputting 3 integers, in mac terminal console, it showed: segmentation fault:11
     #include<stdio.h>
    int main(void)
    {
      int a,b,c = 0;
      float average = 0.0f;
      printf("Please enter three integers you wish to calculate their average:");
      scanf("%d %d %d", a,b,c); //从input把数据放到arithmatic counter里面

      average = (float)(a+b+c)/3.0f;

      printf("\nThe average of the three numbers is:%.2f", average);
      return 0;
      }

1 个答案:

答案 0 :(得分:1)

  

这是两组似乎彼此没有区别的代码,

您需要仔细观察。

请参见scanf()语句:

  • scanf("%d %d %d",&a,&b,&c);是正确的
  • scanf("%d %d %d",a,b,c);是错误的。您的编译器已经对此发出警告。

scanf()期望针对%d提供的参数是整数的指针-为它们提供int(基本上是与预期值不兼容的任何其他类型)将调用{ {3}}。分割错误是副作用之一。