for语句中关于变量的几个问题(新手)
运行环境:winxp,vc6
大家先看一段代码:
#include<stdio.h> /* 这是一个计算三门平均分的程式(共六个学生) */
#include<conio.h>
int main(void)
{
int score[6][3]={0};
double average[3]={0}; /* declaration */
printf("\nplease input the score as followings :chinese maths english\n"); /* input */
for(int i=0;i<=5;i++)
{
printf("\nplease input the number%d student's score\n",i+1);
for(int j=0;j<=2;j++)
scanf("%d",&score[i][j]);
}
for(int k=0;k<=2;k++) /* caculate */
{
for(int a=0;a<=5;a++)
average[k]+=score[a][k];
}
for(int i=0;i<=2;i++) /* 这里出错 */
average[i]=average[i]/6.0;
printf("the average score of chinese is %lf\n",average[0]); /* output */
printf("the average score of maths is %lf\n",average[1]);
printf("the average score of english is %lf\n",average[2]);
getch();
return 0;
}
编译不能通过:H:\Visual c++\test2\source1.cpp(25) : error C2374: 'i' : redefinition; multiple initialization
H:\Visual c++\test2\source1.cpp(11) : see declaration of 'i'
执行 cl.exe 时出错.
我把出错处for语句中的int删去,编译可以通过。
问题1:在c语言中,循环语句中定义的变量怎么可以在循环语句结束后依然存在?
问题2:c99中变量似乎不能定义在for()中,要定义在循环之前,vc6是因为这个影响吗?,c89是如何规定的,我是初学者不太搞得清,望大神能系统的讲一下。
[解决办法]
C89 和C99 的区别,你可以去查找。。。
[解决办法]
VC6.0中 for中定义的int可以在for外部使用的.
而VS中,则不行. 所以注意这个区别就行了, 想通用的话,把int放到for外面定义,for内只作初始化.
[解决办法]
这个是vc6作用域扩大的bug,不是什么c89的问题
在vc6下,你扩展名是cpp的一样有这个问题