visual在C++中的if语句中的数组中使用特定值

visual Use a specific value in an array in an if statement in C++

本文关键字:数组 中的 C++ if 语句 visual      更新时间:2023-10-16
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位于基因1[]和/或基因2[]的第20个位置,则该人将是贫血患者(如果只有一个数组)或携带者(如果在两个数组中)。

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

注意:我注意到我在代码中使用了20而不是19。我做了那个修正,所以忽略它。

谢谢大家!

(这不是一个很好的答案,但很难用注释来表达,由此产生的简化可能会让你找到答案…)

功能分解是你的朋友:

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更难介绍,而且在你介绍的时候更容易发现

编辑:@MarkB指出了我的逻辑中的一个错误(我误读了原始逻辑)。不幸的是,我不确定如何修复它,因为最初的逻辑形式是:

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

由于(A或B)在(A和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 lambdas,您实际上可以在本地声明type()函数到所讨论的函数:

auto type = [](const char* gene1, const char* gene2) -> const char * {
…
};