2
if(gene1A[20] == 'T' || gene2A[20] == 'T')
    outFile << "Person A is of 'Anemic' type." << endl;
else if(gene1A[20] == 'T' && gene2A[20] == 'T')
    outFile << "Person A if of 'Carrier' type." << endl;
else
    outFile << "Person A is of 'Normal' type." << endl;

if(gene1B[20] == 'T' || gene2B[20] == 'T')
    outFile << "Person B is of 'Anemic' type." << endl;
else if(gene1B[20] == 'T' && gene2B[20] == 'T')
    outFile << "Person B if of 'Carrier' type." << endl;
else
    outFile << "Person B is of 'Normal' type." << endl;

if(gene1C[20] == 'T' || gene2C[20] == 'T')
    outFile << "Person C is of 'Anemic' type." << endl;
else if(gene1C[20] == 'T' && gene2C[20] == 'T')
    outFile << "Person C if of 'Carrier' type." << endl;
else
    outFile << "Person C is of 'Normal' type." << endl;

if(gene1D[20] == 'T' || gene2D[20] == 'T')
    outFile << "Person D is of 'Anemic' type." << endl;
else if(gene1A[20] == 'T' && gene2A[20] == 'T')
    outFile << "Person D if of 'Carrier' type." << endl;
else
    outFile << "Person D is of 'Normal' type." << endl;

是我现在的代码。我需要做的是根据我设置的数组输出“outFile”,如果这个人是贫血、携带者或正常人。每个数组有 444 个字符长,可以是 A、C、T 或 O。如果 T 位于gene1[] 和/或gene2[] 的第 20 位,则此人将贫血(如果只有一个数组)或一个载体(如果在两个数组中)。

我现在拥有的东西使它们自动成为“正常”。我相信我的 if 语句设置不正确,但我需要的是引用数组中的第 20 个值,然后如果它 == 'T',则输出它们的“类型”。

注意:我注意到在我的代码中我输入了 20 而不是 19。我进行了更正,所以请看过去。

多谢你们!

4

1 回答 1

1

(这不是一个完整的答案,但很难表达为评论,并且由此产生的简化可能会引导您找到答案......)

功能分解是你的朋友:

const char* type(const char* gene1, const char* gene2) {
    return gene1[19] != 'T' ? "Normal" : gene2[19] == 'T' ? "Anemic" : "Carrier";
}
⋮
outFile << "Person A is of '" << type(gene1A, gene2A) << "' type." << endl;
outFile << "Person B is of '" << type(gene1B, gene2B) << "' type." << endl;
outFile << "Person C is of '" << type(gene1C, gene2C) << "' type." << endl;
outFile << "Person D is of '" << type(gene1D, gene2D) << "' type." << endl;

它还使得像你为 D 人介绍的 bug 这样的 bug 更难介绍,而且当你这样做时更容易发现。

编辑: @MarkB 指出了我的逻辑错误(我误读了原始逻辑)。不幸的是,我不确定如何解决它,因为原始逻辑是以下形式:

     if A or  B then X
else if A and B then Y
else                 Z

因为只要 (A and B) 为真, (A or B) 就为真,第二个子句永远不会触发,这几乎肯定不是你的意图。如果您打算首先使用 AND 子句,则type()可以这样重写该函数:

const char* type(const char* gene1, const char* gene2) {
    bool t1 = gene1[19] == 'T';
    bool t2 = gene2[19] == 'T';
    return t1 && t2 ? "Anemic" : t1 || t2 ? "Carrier" : "Normal"  );
}

顺便说一句,这个函数不会是当前代码的“子函数”(不管这意味着什么),它只是一个在函数上方声明的自由函数。OTOH,如果您的编译器支持 C++11 lambda,您实际上可以在type()本地将函数声明为相关函数:

auto type = [](const char* gene1, const char* gene2) -> const char * {
    …
};
于 2012-11-27T02:36:26.983 回答