C++数组和值的写入
C++ Arrays and writing of values
我正在尝试为生物课编写一个 punnett 方形生成器,这很简单,但我无法弄清楚如何获取要写入其他块的值。我可以输入各个变量,但我无法将值组合在较低的平方中。任何帮助将不胜感激。代码附在下面。
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char p_s[2][2] = {0};
int i = 0;
int j = 1;
cout << "Input first parent's first gene.n";
cin >> p_s[i][j];
j++;
cout << "Input first parent's sencond gene.n";
cin >> p_s[i][j];
system("Pause");
cout << "First Gene: " << p_s[0][1] << endl << endl << "Second Gene: " << p_s[0][2];
j = 0;
i++;
cout << endl << endl << "Input second parent's first gene: ";
cin >> p_s[i][j];
i++;
cout << "Input second parent's second gene: ";
cin >> p_s[i][j];
cout << "First Gene: " << p_s[1][0] << endl << endl << "Second Gene: " << p_s[0][2];
system("PAUSE");
p_s[1][1] = p_s[0][1] p_s[1][0];
cout << p_s[1][1];
return 0;
}
首先,我可以看到int j
的问题:
在第三行中,将其初始化为一
int j = 1;
三行后,您将它向上递增一:
j++; // j is now equal to 2
//...
cin >> p_s[i][j]; // j is still equal to 2, which is outside of the array bounds!
同样的事情发生在第 10 行和第 18 行,您尝试访问 p_s[0][2]
,这超出了数组的边界。
此外,如果你想制作一个传统的punnett正方形,每个方块需要两char
的存储空间,这是你当前的系统所没有的(你需要8个char
,而p_s
只有四个)。
但是,如果你想修改你的程序,你总是可以尝试一种面向对象的方法,把你的小朋友和父母分成这样的类:
struct Parent
{
std::string a;
std::string b;
Parent(std::string _a, std::string _b) : a(_a), b(_b) {}
}
和
struct Punnett
{
std::vector<std::string> GeneCombos;
Punnett (Parent one, Parent two) {
GeneCombos.push_back(one.a + two.a);
GeneCombos.push_back(one.a + two.b);
GeneCombos.push_back(one.b + two.a);
GeneCombos.push_back(one.b + two.b);
}
}
这样你就不必担心 Punnett 正方形的值:它们是在构造函数中创建的。
如果你想更进一步,你可以添加到两个类的构造函数中,使它们根据用户输入分配变量:
struct Parent
{
std::string a;
std::string b;
Parent(std::string _a, std::string _b) : a(_a), b(_b) {}
Parent() { //If no values are passed, it asks for them
std::cout << "nEnter Gene One: ";
std::cin >> a;
std::cout << "nEnter Gene Two: ";
std::cin >> b;
}
};
对于庞内特类:
class Punnett
{
std::vector<std::string> GeneCombos;
public:
void draw() {
std::cout << "nResulting Combinations:n";
for (unsigned int i = 0; i < 4; ++i)
std::cout << GeneCombos[i] << 'n';
}
Punnett (Parent one, Parent two) {
GeneCombos.push_back(one.a + two.a);
GeneCombos.push_back(one.a + two.b);
GeneCombos.push_back(one.b + two.a);
GeneCombos.push_back(one.b + two.b);
}
};
使用修改后的类,main() 只有五行长:
int main()
{
Parent One;
Parent Two;
Punnett punnett(One, Two);
punnett.draw();
return 0;
}
希望这有帮助。
编辑*:正如Ben Voigt明智地指出的那样,Punnett::d raw()函数不属于构造函数,并被移至main()。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '