C 在输出平均数时,程序呈现分段错误11
下面是两组代码,它们似乎没有什么不同,但其中一组生成警告和分段错误11C 在输出平均数时,程序呈现分段错误11,c,scanf,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
//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;
}
//结果正常的程序
#包括
int main()
{int a,b,c,d;浮点数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);
返回0;
}
//伴随小问题而来的计划
//format指定类型“int*”,但参数的类型为“int”[-Wformat]
//输入3个整数后,在mac终端控制台显示:分段错误:11
#包括
内部主(空)
{
int a,b,c=0;
浮动平均值=0.0f;
printf(“请输入三个您希望计算其平均值的整数:”);
scanf(“%d%d%d”,a、b、c)//从输入把数据放到算术计数器里面
平均值=(浮动)(a+b+c)/3.0f;
printf(“\n三个数字的平均值为:%.2f”,平均值);
返回0;
}
这里有两组代码看起来没有什么不同
你需要仔细观察。
请参阅scanf()
语句:
scanf(“%d%d%d”,&a,&b,&c)代码>是正确的
scanf(“%d%d%d”,a、b、c)代码>是错误的。你的编译器已经警告过你了
scanf()
希望针对%d
提供的参数是指向整数的指针-将调用为它们提供int
s(基本上是针对预期类型的任何其他不兼容类型)。分段错误是副作用之一。调用scanf()
需要传递a
、b
和c
的地址。i、 e.scanf(“%d%d%d”、&a、&b和&c)
如果没有符号,行为是未定义的。