C++数组和值的写入

C++ Arrays and writing of values

本文关键字:数组 C++      更新时间:2023-10-16

我正在尝试为生物课编写一个 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()。