- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
不断出现代码错误,这是从旧 VS 到 2010 版本的转换:
#include <string>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <math.h>
using std::string;
#define CROSSOVER_RATE 0.7
#define MUTATION_RATE 0.001
#define POP_SIZE 100 //must be an even number
#define CHROMO_LENGTH 300
#define GENE_LENGTH 4
#define MAX_ALLOWABLE_GENERATIONS 400
//returns a float between 0 & 1
#define RANDOM_NUM ((float)rand()/(RAND_MAX+1))
//----------------------------------------------------------------------------------------
//
// define a data structure which will define a chromosome
//
//----------------------------------------------------------------------------------------
struct chromo_typ
{
//the binary bit string is held in a std::string
string bits;
float fitness;
chromo_typ(): bits(""), fitness(0.0f){};
chromo_typ(string bts, float ftns): bits(bts), fitness(ftns){}
};
/////////////////////////////////prototypes/////////////////////////////////////////////////////
void PrintGeneSymbol(int val);
string GetRandomBits(int length);
int BinToDec(string bits);
float AssignFitness(string bits, int target_value);
void PrintChromo(string bits);
void PrintGeneSymbol(int val);
int ParseBits(string bits, int* buffer);
string Roulette(int total_fitness, chromo_typ* Population);
void Mutate(string &bits);
void Crossover(string &offspring1, string &offspring2);
//-------------------------------main--------------------------------------------------
//
//-------------------------------------------------------------------------------------
int main()
{
//seed the random number generator
srand((int)time(NULL));
//just loop endlessly until user gets bored :0)
while (true)
{
//storage for our population of chromosomes.
chromo_typ Population[POP_SIZE];
//get a target number from the user. (no error checking)
float Target;
cout << "\nInput a target number: ";
cin >> Target;
cout << endl << endl;
//first create a random population, all with zero fitness.
for (int i=0; i<POP_SIZE; i++)
{
Population[i].bits = GetRandomBits(CHROMO_LENGTH);
Population[i].fitness = 0.0f;
}
int GenerationsRequiredToFindASolution = 0;
//we will set this flag if a solution has been found
bool bFound = false;
//enter the main GA loop
while(!bFound)
{
//this is used during roulette wheel sampling
float TotalFitness = 0.0f;
// test and update the fitness of every chromosome in the
// population
for (int i=0; i<POP_SIZE; i++)
{
Population[i].fitness = AssignFitness(Population[i].bits, Target);
TotalFitness += Population[i].fitness;
}
// check to see if we have found any solutions (fitness will be 999)
for (i=0; i<POP_SIZE; i++)
{
if (Population[i].fitness == 999.0f)
{
cout << "\nSolution found in " << GenerationsRequiredToFindASolution << " generations!" << endl << endl;;
PrintChromo(Population[i].bits);
bFound = true;
break;
}
}
// create a new population by selecting two parents at a time and creating offspring
// by applying crossover and mutation. Do this until the desired number of offspring
// have been created.
//define some temporary storage for the new population we are about to create
chromo_typ temp[POP_SIZE];
int cPop = 0;
//loop until we have created POP_SIZE new chromosomes
while (cPop < POP_SIZE)
{
// we are going to create the new population by grabbing members of the old population
// two at a time via roulette wheel selection.
string offspring1 = Roulette(TotalFitness, Population);
string offspring2 = Roulette(TotalFitness, Population);
//add crossover dependent on the crossover rate
Crossover(offspring1, offspring2);
//now mutate dependent on the mutation rate
Mutate(offspring1);
Mutate(offspring2);
//add these offspring to the new population. (assigning zero as their
//fitness scores)
temp[cPop++] = chromo_typ(offspring1, 0.0f);
temp[cPop++] = chromo_typ(offspring2, 0.0f);
}//end loop
//copy temp population into main population array
for (i=0; i<POP_SIZE; i++)
{
Population[i] = temp[i];
}
++GenerationsRequiredToFindASolution;
// exit app if no solution found within the maximum allowable number
// of generations
if (GenerationsRequiredToFindASolution > MAX_ALLOWABLE_GENERATIONS)
{
cout << "No solutions found this run!";
bFound = true;
}
}
cout << "\n\n\n";
}//end while
return 0;
}
//---------------------------------GetRandomBits-----------------------------------------
//
// This function returns a string of random 1s and 0s of the desired length.
//
//-----------------------------------------------------------------------------------------
string GetRandomBits(int length)
{
string bits;
for (int i=0; i<length; i++)
{
if (RANDOM_NUM > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
//---------------------------------BinToDec-----------------------------------------
//
// converts a binary string into a decimal integer
//
//-----------------------------------------------------------------------------------
int BinToDec(string bits)
{
int val = 0;
int value_to_add = 1;
for (int i = bits.length(); i > 0; i--)
{
if (bits.at(i-1) == '1')
val += value_to_add;
value_to_add *= 2;
}//next bit
return val;
}
//---------------------------------ParseBits------------------------------------------
//
// Given a chromosome this function will step through the genes one at a time and insert
// the decimal values of each gene (which follow the operator -> number -> operator rule)
// into a buffer. Returns the number of elements in the buffer.
//------------------------------------------------------------------------------------
int ParseBits(string bits, int* buffer)
{
//counter for buffer position
int cBuff = 0;
// step through bits a gene at a time until end and store decimal values
// of valid operators and numbers. Don't forget we are looking for operator -
// number - operator - number and so on... We ignore the unused genes 1111
// and 1110
//flag to determine if we are looking for an operator or a number
bool bOperator = true;
//storage for decimal value of currently tested gene
int this_gene = 0;
for (int i=0; i<CHROMO_LENGTH; i+=GENE_LENGTH)
{
//convert the current gene to decimal
this_gene = BinToDec(bits.substr(i, GENE_LENGTH));
//find a gene which represents an operator
if (bOperator)
{
if ( (this_gene < 10) || (this_gene > 13) )
continue;
else
{
bOperator = false;
buffer[cBuff++] = this_gene;
continue;
}
}
//find a gene which represents a number
else
{
if (this_gene > 9)
continue;
else
{
bOperator = true;
buffer[cBuff++] = this_gene;
continue;
}
}
}//next gene
// now we have to run through buffer to see if a possible divide by zero
// is included and delete it. (ie a '/' followed by a '0'). We take an easy
// way out here and just change the '/' to a '+'. This will not effect the
// evolution of the solution
for (i=0; i<cBuff; i++)
{
if ( (buffer[i] == 13) && (buffer[i+1] == 0) )
buffer[i] = 10;
}
return cBuff;
}
//---------------------------------AssignFitness--------------------------------------
//
// given a string of bits and a target value this function will calculate its
// representation and return a fitness score accordingly
//------------------------------------------------------------------------------------
float AssignFitness(string bits, int target_value)
{
//holds decimal values of gene sequence
int buffer[(int)(CHROMO_LENGTH / GENE_LENGTH)];
int num_elements = ParseBits(bits, buffer);
// ok, we have a buffer filled with valid values of: operator - number - operator - number..
// now we calculate what this represents.
float result = 0.0f;
for (int i=0; i < num_elements-1; i+=2)
{
switch (buffer[i])
{
case 10:
result += buffer[i+1];
break;
case 11:
result -= buffer[i+1];
break;
case 12:
result *= buffer[i+1];
break;
case 13:
result /= buffer[i+1];
break;
}//end switch
}
// Now we calculate the fitness. First check to see if a solution has been found
// and assign an arbitarily high fitness score if this is so.
if (result == (float)target_value)
return 999.0f;
else
return 1/(float)fabs((double)(target_value - result));
// return result;
}
//---------------------------------PrintChromo---------------------------------------
//
// decodes and prints a chromo to screen
//-----------------------------------------------------------------------------------
void PrintChromo(string bits)
{
//holds decimal values of gene sequence
int buffer[(int)(CHROMO_LENGTH / GENE_LENGTH)];
//parse the bit string
int num_elements = ParseBits(bits, buffer);
for (int i=0; i<num_elements; i++)
{
PrintGeneSymbol(buffer[i]);
}
return;
}
//--------------------------------------PrintGeneSymbol-----------------------------
//
// given an integer this function outputs its symbol to the screen
//----------------------------------------------------------------------------------
void PrintGeneSymbol(int val)
{
if (val < 10 )
cout << val << " ";
else
{
switch (val)
{
case 10:
cout << "+";
break;
case 11:
cout << "-";
break;
case 12:
cout << "*";
break;
case 13:
cout << "/";
break;
}//end switch
cout << " ";
}
return;
}
//------------------------------------Mutate---------------------------------------
//
// Mutates a chromosome's bits dependent on the MUTATION_RATE
//-------------------------------------------------------------------------------------
void Mutate(string &bits)
{
for (int i=0; i<bits.length(); i++)
{
if (RANDOM_NUM < MUTATION_RATE)
{
if (bits.at(i) == '1')
bits.at(i) = '0';
else
bits.at(i) = '1';
}
}
return;
}
//---------------------------------- Crossover ---------------------------------------
//
// Dependent on the CROSSOVER_RATE this function selects a random point along the
// lenghth of the chromosomes and swaps all the bits after that point.
//------------------------------------------------------------------------------------
void Crossover(string &offspring1, string &offspring2)
{
//dependent on the crossover rate
if (RANDOM_NUM < CROSSOVER_RATE)
{
//create a random crossover point
int crossover = (int) (RANDOM_NUM * CHROMO_LENGTH);
string t1 = offspring1.substr(0, crossover) + offspring2.substr(crossover, CHROMO_LENGTH);
string t2 = offspring2.substr(0, crossover) + offspring1.substr(crossover, CHROMO_LENGTH);
offspring1 = t1; offspring2 = t2;
}
}
//--------------------------------Roulette-------------------------------------------
//
// selects a chromosome from the population via roulette wheel selection
//------------------------------------------------------------------------------------
string Roulette(int total_fitness, chromo_typ* Population)
{
//generate a random number between 0 & total fitness count
float Slice = (float)(RANDOM_NUM * total_fitness);
//go through the chromosones adding up the fitness so far
float FitnessSoFar = 0.0f;
for (int i=0; i<POP_SIZE; i++)
{
FitnessSoFar += Population[i].fitness;
//if the fitness so far > random number return the chromo at this point
if (FitnessSoFar >= Slice)
return Population[i].bits;
}
return "";
}
我得到的错误是:
error C2065: 'cin' : undeclared identifier
error C2065: 'cout' : undeclared identifier
error C2065: 'endl' : undeclared identifier
error C2065: 'i' : undeclared identifier
error C2228: left of '.bits' must have class/struct/union
error C2228: left of '.fitness' must have class/struct/union
最佳答案
您要么想要 std::cin
(等),要么在源文件顶部使用 using std::cin;
。
至于i
的问题;好吧,你有一个使用 i
而不声明它的循环(这反过来也导致了 .bits
和 .fitness
的问题.
关于c++ - 未声明的标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6190510/
#include using namespace std; class C{ private: int value; public: C(){ value = 0;
这个问题已经有答案了: What is the difference between char a[] = ?string?; and char *p = ?string?;? (8 个回答) 已关闭
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 此帖子已于 8 个月
除了调试之外,是否有任何针对 c、c++ 或 c# 的测试工具,其工作原理类似于将独立函数复制粘贴到某个文本框,然后在其他文本框中输入参数? 最佳答案 也许您会考虑单元测试。我推荐你谷歌测试和谷歌模拟
我想在第二台显示器中移动一个窗口 (HWND)。问题是我尝试了很多方法,例如将分辨率加倍或输入负值,但它永远无法将窗口放在我的第二台显示器上。 关于如何在 C/C++/c# 中执行此操作的任何线索 最
我正在寻找 C/C++/C## 中不同类型 DES 的现有实现。我的运行平台是Windows XP/Vista/7。 我正在尝试编写一个 C# 程序,它将使用 DES 算法进行加密和解密。我需要一些实
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
有没有办法强制将另一个 窗口置于顶部? 不是应用程序的窗口,而是另一个已经在系统上运行的窗口。 (Windows, C/C++/C#) 最佳答案 SetWindowPos(that_window_ha
假设您可以在 C/C++ 或 Csharp 之间做出选择,并且您打算在 Windows 和 Linux 服务器上运行同一服务器的多个实例,那么构建套接字服务器应用程序的最明智选择是什么? 最佳答案 如
你们能告诉我它们之间的区别吗? 顺便问一下,有什么叫C++库或C库的吗? 最佳答案 C++ 标准库 和 C 标准库 是 C++ 和 C 标准定义的库,提供给 C++ 和 C 程序使用。那是那些词的共同
下面的测试代码,我将输出信息放在注释中。我使用的是 gcc 4.8.5 和 Centos 7.2。 #include #include class C { public:
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我的客户将使用名为 annoucement 的结构/类与客户通信。我想我会用 C++ 编写服务器。会有很多不同的类继承annoucement。我的问题是通过网络将这些类发送给客户端 我想也许我应该使用
我在 C# 中有以下函数: public Matrix ConcatDescriptors(IList> descriptors) { int cols = descriptors[0].Co
我有一个项目要编写一个函数来对某些数据执行某些操作。我可以用 C/C++ 编写代码,但我不想与雇主共享该函数的代码。相反,我只想让他有权在他自己的代码中调用该函数。是否可以?我想到了这两种方法 - 在
我使用的是编写糟糕的第 3 方 (C/C++) Api。我从托管代码(C++/CLI)中使用它。有时会出现“访问冲突错误”。这使整个应用程序崩溃。我知道我无法处理这些错误[如果指针访问非法内存位置等,
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我有一些 C 代码,将使用 P/Invoke 从 C# 调用。我正在尝试为这个 C 函数定义一个 C# 等效项。 SomeData* DoSomething(); struct SomeData {
这个问题已经有答案了: Why are these constructs using pre and post-increment undefined behavior? (14 个回答) 已关闭 6
我是一名优秀的程序员,十分优秀!