1

我必须比较两个数组,每个数组都有 444 个字符,如果它们完全相同,则输出它们是相同的。如果不是,那么程序将继续运行,直到完成所有数组的相互比较。

到目前为止,这是我的代码。我已经对其进行了多次更改,但我要么让程序不向 outFile 输出任何内容(说没有一个是相同的,我认为这是错误的,因为我想一个会是相同的,或者教授不会要求我们这样做)或者它说每个基因链都是相同的:

#include iostream
#include string
#include fstream
using namespace std;

ifstream inFile;
ofstream outFile;


bool SameGene(char gene1[], char gene2[], int size)

{
    for(int i=0, j=0;i<444 && j<444;i++,j++)
        if(gene1[i] != gene2[j])
            return false;

    return true;
}


int main()
{

    inFile.open("dna.txt");
    outFile.open("DNAanalysis.txt.");

    char gene1A[444], gene2A[444];

    char gene1B[444], gene2B[444];

    char gene1C[444], gene2C[444];

    char gene1D[444], gene2D[444];

    inFile.read(gene1A, 444);
    inFile.read(gene2A, 444);
    inFile.read(gene1B, 444);
    inFile.read(gene2B, 444);
    inFile.read(gene1C, 444);
    inFile.read(gene2C, 444);
    inFile.read(gene1D, 444);
    inFile.read(gene2D, 444);

    if(SameGene(gene1A, gene1B, 444) || SameGene(gene2A, gene2B, 444))
        outFile << "Person A and Person B are related." << endl;
    if(SameGene(gene1A, gene1C, 444) || SameGene(gene2A, gene2C, 444))
        outFile << "Person A and Person C are related." << endl;
    if(SameGene(gene1A, gene1D, 444) || SameGene(gene2A, gene2D, 444))
        outFile << "Person A and Person D are related." << endl;
    if(SameGene(gene1B, gene1C, 444) || SameGene(gene2B, gene2C, 444))
        outFile << "Person B and Person C are related." << endl;
    if(SameGene(gene1B, gene1D, 444) || SameGene(gene2B, gene2D, 444))
        outFile << "Person B and Person D are related." << endl;
    if(SameGene(gene1C, gene1D, 444) || SameGene(gene2C, gene2D, 444))
        outFile << "Person C and Person D are related." << endl;

    return 0;
}
4

1 回答 1

1

您可以使用std::equal比较两个数组:

#include <algorithm>

bool same = std::equal(gene1, gene1+444, gene2);

在这里你必须确保gene2至少与gene1.

如果你的问题出在其他地方,那么你应该在问题的标题中明确这一点,并专注于真正的问题。

于 2012-11-25T18:42:08.917 回答