【问题标题】:Display output in row and column在行和列中显示输出
【发布时间】:2016-10-14 08:52:11
【问题描述】:

我想显示如下输出:

Count      Input       Total  
-----      ------      -----  
1                 2           2  
2               4           6  
3               6           12  
4               8           20

Average : 5

这是我的尝试:

int count=1,num,total=0;
cout<<"Count    Input   Total"<<endl;
cout<<"-----    -----   -----"<<"\n";
while(count<=4)
{
    cout<<count<<"\t";
    cin>>num;
    total=total+num;
    cout<<"\t\t"
        <<total<<endl;
    count++;
}
cout<<"Average : "
    <<total/4;

return 0;
}  

但结果是这样的:

Count   Input   Total  
-----   -----   -----  
1       2  
                      2  
2       4  
                6  
3       6  
                12  
4       8  
                20  
Average : 5
--------------------------------
Process exited after 5.785 seconds with return value 0
Press any key to continue . . .

【问题讨论】:

    标签: c++ arrays input output


    【解决方案1】:

    您将程序的输出与键盘的输入混合在一起,两者都显示在同一个控制台上。

    cin>>num 从控制台输入的输入只有在你按下键盘上的“enter”后才会被接收,这反过来也会导致屏幕上的输出转到下一行。

    如果您想禁止“输入”将光标移动到屏幕上的下一行,这在 c++ 中无法轻松完成,通常在 Linux 或 Windows 或其他操作系统中有方法可以这样做(stty -echo ,回声关闭,等等)。但这也会抑制输入的整数出现,因此在您的代码中,您需要在它们进入时将它们打印出来。

    但是,人们通常不会尝试将键盘的输出与程序的输出混合成表格等连贯的东西。您的程序可以简单地首先要求键盘输入,将该输入存储到一个数组或向量中,然后使用该输入写入您的表格。很可能这就是问题要求您做的事情。

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    void output(vector<int> &vals) {
        unsigned int count = 1;
        int total = 0;
        cout << "Count\tInput\tTotal" << endl;
        cout << "-----\t-----\t-----" << endl;
        while (count <= vals.size()) {
            int num = vals[count - 1];
            total += num;
            cout << count << "\t" << num << "\t" << total << endl;
            count++;
        }
        cout << "Average : " << total / (count - 1) << endl;
    }
    
    vector<int> input() {
        vector<int> vals;
        for (int i = 0; i < 4; i++) {
            int num;
            cin >> num;
            vals.push_back(num);
        }
        return vals;
    }
    
    int main() {
        output(input());
    }
    
    
    5
    7
    2
    11
    Count   Input   Total
    -----   -----   -----
    1       5       5
    2       7       12
    3       2       14
    4       11      25
    Average : 6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多