Hi everyone. I am new to C++ programming. I need to calculate the fitness for each of startNode[i] and store it into new array. I had try to do it but error appear "error C2109: subscript requires array or pointer type". I don't know how to correct this error. Hoping anyone can help me.
This is my input file in (.txt). First column refer to startNode and second coumn is objFunction.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
usingnamespace std;
int main()
{
int i;
constint Initial_Population = 5;
int startNode [Initial_Population];
double objFunction [Initial_Population];
ifstream inputFile;
inputFile.open ("myFile.txt");
//store data into array.
for (i = 0; i < Initial_Population; i++)
{
inputFile >> startNode[i];
inputFile >> objFunction[i];
}
inputFile.close();
//declare max & min & fitness.
double max = objFunction [0];
double min = objFunction [0];
double fitness;
for (int i = 0; i < Initial_Population; i++)
{
//finding the maximum value z in array.
if (objFunction[i] > max)
{
max = objFunction[i];
}
//finding the minimum value z in array.
elseif (objFunction[i] < min)
{
min = objFunction[i];
}
}
//calculate the fitness for each startNode[i].
for (int i = 0; i < Initial_Population; i++)
{
fitness[i] = ((max - objFunction[i]) / (max - min));
}
cout << "fitness value: " << fitness << endl;
system("pause");
return 0;
}
#include <iostream>
#include <fstream>
int main()
{
constint Initial_Population = 5;
int startNode [Initial_Population];
double objFunction [Initial_Population];
//store data into array.
{
// open the file for input
std::ifstream inputFile("myFile.txt");
// we assume that the input file was opened successfully and contains valid data
for( int i = 0; i < Initial_Population; ++i )
inputFile >> startNode[i] >> objFunction[i];
// the file is automagically closed when the scope is exited
}
double max = objFunction [0];
double min = objFunction [0];
for( int i = 0; i < Initial_Population; ++i )
{
if( objFunction[i] > max ) max = objFunction[i];
elseif( objFunction[i] < min ) min = objFunction[i];
}
// calculate the fitness for each startNode[i] and print it out.
constdouble diff = max - min ;
if( diff > 0 )
{
for( int i = 0; i < Initial_Population; ++i )
{
// note: fitness is not an array
constdouble fitness = ( max - objFunction[i] ) / diff ;
std::cout << "node: " << startNode[i] << " "
<< "fitness value: " << fitness << '\n' ;
}
}
else std::cout << "max == min; infinite fitness for all\n" ;
}