以行和列显示输出

Display output in row and column

本文关键字:显示 输出      更新时间:2023-10-16

我想显示如下输出:

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<<"tt"
        <<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 . . .

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

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

如果您想要在光标移动到屏幕上的下一行时禁用"enter",这在c++中很难做到,通常在Linux或Windows或其他操作系统中有很多方法可以做到(stty -echo, echo off,等等)。但是这样也会抑制键入的整数出现,因此在代码中,您需要在它们出现时将它们打印出来。

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

#include <iostream>
#include <vector>
using namespace std;
void output(vector<int> &vals) {
    unsigned int count = 1;
    int total = 0;
    cout << "CounttInputtTotal" << 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