visual在C++中的if语句中的数组中使用特定值
visual Use a specific value in an array in an if statement in C++
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 * {
…
};
相关文章:
- 试图让变量检查数组中的某些内容
- 使用for循环检查数组中的重复项
- 对字符数组中的元素执行逐位操作
- 按平均值替换数组中的元素
- 移动二维数组中的字符
- 打印矢量数组中的所有元素
- 字符数组中的元素数
- 使用指针访问数组中的对象数据成员
- 显示数组中的学生 ID 和最高分
- C++数组中的 GLFloat 数组
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 在 C++ 中搜索动态分配的数组中的出现次数
- 如何在 c++ 中格式化和访问 2D 矢量数组中的数据
- 使用 GDAL 获取矢量数组中的所有行数和列数
- 关于字符数组,我正在尝试将数组中的每个字符分配给另一个值
- C++递归来决定数组中的两个值
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- 在C++中访问结构数组中的数据
- 如何在 C++ 中将双精度数组中的值"force convert"到字符串输出中?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?