【问题标题】:A while-loop that reads in two ints and then prints them读取两个整数然后打印它们的 while 循环
【发布时间】:2012-10-19 17:35:12
【问题描述】:

我完全陷入了“编程 - 使用 C++ 的原则和实践”第 4 章的练习中。问题是:

“编写一个由 while 循环组成的程序,该循环(每次围绕循环)读取两个整数,然后打印它们。当终止 '|' 时退出程序已输入。”

这是我的代码:

{
int entryvariable = 0;
int numberofentries = 0;
vector<int>vector1;


while (cin>>entryvariable)
{
    vector1.push_back(entryvariable);
    ++numberofentries;

if (numberofentries % 2 == 0)
    cout<<vector1[numberofentries - 1] << vector1[numberofentries] << "\n";
}

当然,这最终会崩溃。

我将如何解决这个问题以使其正常工作?

(有人有这本书的答案吗?写得真好,但是如果你在自学的话是不可能检查你的答案的。)

【问题讨论】:

  • 您可以读取两个整数:while (cin &gt;&gt; v1 &gt;&gt; v2)。那么就不再需要vector1numberofentries

标签: c++


【解决方案1】:

C++ 中的索引范围从0n - 1。您的代码假定您可以访问vector1[n],如果vector1.size() == n。此外,您在每次迭代中只读取一个值。不过,您只能读取两个值。

【讨论】:

    【解决方案2】:
    int main()
    {
    vector<int>v;
    int a=0; 
    cin>>a; 
    int b=0; 
    while (v.size()<2) // insted of 2 it could be another figure for 
                       //   another number of printed figures
    {
    v.push_back(a); 
    cin>>b;
    a=b;
    }
    for (int i=0; i<v.size(); ++i)
    cout<<v[i]<<'\n';
    }
    

    【讨论】:

    • 在问题中添加问题描述。
    【解决方案3】:

    您的vector1[numberofentries] 导致错误

    一个向量从0thindex..开始。

    因此,当您的 numberofentries 为 1 时,该值存储在 vector1[0] 而不是 vector1[1]

    当您的 numberofentries 为 2 时,该值存储在 vector1[1] 而不是 vector1[2]

    所以你的代码应该是

    cout&lt;&lt;vector1[numberofentries - 2] &lt;&lt; vector1[numberofentries-1] &lt;&lt; "\n";

    【讨论】:

      【解决方案4】:

      我正在做同样的练习,并且发现这本书的谷歌小组是询问有关练习和练习的问题的最佳场所,可以找到与您的问题相关的线程here

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-04
        • 2013-09-25
        • 1970-01-01
        • 1970-01-01
        • 2017-04-29
        • 1970-01-01
        • 2016-07-08
        • 2016-10-22
        相关资源
        最近更新 更多