Page 1 of 1
compile error. help...
Posted: Mon Mar 06, 2006 7:25 am
by winterflower
#include<iostream>
#include<iomanip>
using namespace std;
void main(){
int n;
cin>>n;
int k;
double *p;
while(n-- > 0){
cin>>k;
p = new double[k];
double sum = 0;
for(int i=0;i<k;i++){
cin>>p;
sum += p;
}
int c = 0;
double ave = sum/(double)k;
for(i=0;i<k;i++){
if(p > ave) c++;
}
delete p;
double x = (double)100*c/k;
cout<<setprecision(3)<<setiosflags(ios::fixed)<<x<<"%"<<endl;
}
}
A simple problem but I've got a lot of CE.
Why ?Thanks in advance!!
Posted: Mon Mar 06, 2006 8:49 am
by chunyi81
This part of your code:
Code: Select all
for(i=0;i<k;i++){
if(p[i] > ave) c++;
}
i is undeclared.
Posted: Mon Mar 06, 2006 9:14 am
by winterflower
Thanks a lot!
I got AC now by adding the declaration of the ''int i''.
But I still don't know why this correct code got such result in VC++.
The former code I posted works well in it.
--------------------Configuration: aver - Win32 Debug--------------------
Compiling...
aver.cpp
C:\Mycpp\aver.cpp(21) : error C2374: 'i' : redefinition; multiple initialization
C:\Mycpp\aver.cpp(15) : see declaration of 'i'
Error executing cl.exe.
aver.exe - 1 error(s), 0 warning(s)
Posted: Mon Mar 06, 2006 9:34 am
by sumankar
ANSI C++ Committee defined that the scope of such variable is the scope of
'for' itself. Before this new standard the scope was not defined and developers
of compilers could do what they want.
g++ and VC++(ver x) has different scoping for variables. For g++ the scope is till the closing brace of the loop whereas for VC++ it is till the end of the function (which is *not* the
correct one, as far as the standard goes.)
AFAIK, g++ 2.7.x implemented this change as the default one. Use -fno-for-scope with g++
to get a VC++ like effect.
Posted: Mon Mar 06, 2006 4:31 pm
by Krzysztof Duleba
I'm pretty sure this is a problem with old versions of VC++ only. Those from Visual Studio 2003 and 2005 should conform to the standard.