我的主要功能中只有很少的代码:
cout << "cout working.\n";
GA genetics;
genetics.run();
当我编译它时,编译器没有任何问题,但是当我运行此代码时,cout working
甚至没有显示。奇怪的是,当我拿出genetics.run();
时,它会被打印出来。
因为我真的不知道,这个问题甚至来自哪里我会在这里发布我的全部代码,所以也许你们中的一个可以帮助我。
#include <time.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class GA{
public:
GA(): POPULATION(30), CARDS(10), TARG_SUM(36), TARG_PROD(360), MAX_TOUR(1000), MUT(10), REC(50){};
void run();
private:
const int POPULATION;
const int CARDS;
const int TARG_SUM;
const int TARG_PROD;
const int MAX_TOUR;
const int MUT;
const int REC;
int gene[30][10];
void init_pop();
double evaluate(int n);
void display(int tournaments, int n);
};
int main() {
cout << "cout working.\n";
GA genetics;
genetics.run();
}
void GA::run(){
cout << "run called\n";
int a, b, winner, loser;
init_pop();
for(int round = 0; round < MAX_TOUR; round++){
a = rand()%POPULATION;
b = rand()%POPULATION;
while(a == b){
b = rand()%POPULATION;
cout < "in loop \n";
}
cout << "Testing " << a << " against " << b << endl;
if(evaluate(a) < evaluate(b)){
winner = a;
loser = b;
} else {
winner = b;
loser = a;
}
if(evaluate(winner) == 0.0){
display(round, winner);
}
for(int i=0; i<CARDS; i++){
if(rand()%100 < REC)
gene[loser][i] = gene[winner][i];
if(rand()%100 < MUT)
gene[loser][i] = 1-gene[loser][i]; //invertiert gen
if(evaluate(loser) == 0.0)
display(round, loser);
}
}
}
void GA::init_pop(){
cout << "called";
srand(time(NULL));
for(int n = 0; n < POPULATION; n++){
for(int i = 0; i < CARDS; i++){
i = rand()%2;
}
}
}
double GA::evaluate(int n){
int sum = 0, prod = 1;
double sum_error, prod_error, combined_error;
for(int i=0; i<10; i++){
if(gene[n,i] == 0){
sum += (1+i);
} else {
prod *= (1+i);
}
}
sum_error = (sum-TARG_SUM)/TARG_SUM;
prod_error = (prod-TARG_PROD)/TARG_PROD;
combined_error = abs(sum_error)+abs(prod_error);
return combined_error;
}
void GA::display(int tournaments, int n){
cout << "\n\n Tournaments: " << tournaments <<"\n Solution sum pile: (should be 36) are:\n";
for(int i=0; i<CARDS; i++){
if(gene[n][i] == 1)
cout << i+1 << endl;
}
cout << "The results for the product pile (should be 360) are:\n";
for(int i=0; i<CARDS; i++){
if(gene[n][i] == 0)
cout << i+1 << endl;
}
}