簡體   English   中英

C++ Arrays 和值的寫入

[英]C++ Arrays and writing of values

我正在嘗試為生物 class 編寫一個 pu.nett 方形生成器,它非常簡單,但我無法弄清楚如何獲取要寫入其他塊的值。 我可以獲取單個變量,但無法獲取要在下方方塊中組合的值。 任何幫助,將不勝感激。 代碼附在下面。

#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的問題:

在第三行,你將它初始化為 1

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]

另外,如果你想制作一個傳統的 pu.nett 正方形,每個正方形需要兩個char的存儲空間,這在你當前的系統中是不可用的(你需要 8 個charp_s只有四個)。

然而,如果你想修改你的程序,你總是可以嘗試一種面向 object 的方法,將你的 pu.nett 和父母分成這樣的類:

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);
    }
}

這樣您就不必擔心 Pu.nett 正方形的值:它們是在構造函數中創建的。

如果你想 go 更進一步,你可以添加到兩個類的構造函數中,使它們根據用戶輸入分配變量:

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;
    }
};

對於 Pu.nett class:

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 明智地指出的那樣,Pu.nett::draw() function 不屬於構造函數,而是移到了 main() 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM