0

我为类编写了一个程序,它使用 for 循环让用户输入一个值,它为您提供了一个带有循环计数器、输入的显示编号和产品的表格。我试图让每列中所有 10 个数字的总和显示在每列的末尾。我很困惑如何对每一列求和并将其显示在下面。任何帮助都会很棒!我正在使用 Visual Studio Express 2012

#include <iostream>
#include <iomanip> 
using namespace std;

int main()
{

int input;

cout << "Enter Value: ";
cin >> input;
cout << "Loop Counter" << setw(20) << "Number Entered" << setw(14) << "Product" << endl;

for(int counter = 1; counter <= 10; counter++)

{
    int product = input * counter;

    if (product < 10 && counter != 10)
        cout << setw(6) << counter << setw(17) << input << setw(17) << product << endl;  
    else if (product > 10 && counter != 10)
        cout << setw(6) << counter << setw(17) << input << setw(18) << product << endl; 
    else
        cout << setw(7) << counter << setw(16) << input << setw(18) << product << endl;
}
cout<<setfill('_')<<setw(45)<<"_"<<endl;
}
4

1 回答 1

0

您需要对单独变量中的列值求和。像这样更改您的代码:

#include <iostream>
#include <iomanip> 
using namespace std;

int main() {

    int input = 0;

    cout << "Enter Value: ";
    cin >> input;
    cout << "Loop Counter" << setw(20) << "Number Entered" << setw(14) << "Product" << endl;

    int counterSum = 0;
    int inputSum = 0;
    int productSum = 0;
    for(int counter = 1; counter <= 10; counter++) {
        int product = input * counter;

        if (product < 10 && counter != 10)
            cout << setw(6) << counter << setw(17) << input << setw(17) << product << endl;  
        else if (product > 10 && counter != 10)
            cout << setw(6) << counter << setw(17) << input << setw(18) << product << endl; 
        else
            cout << setw(7) << counter << setw(16) << input << setw(18) << product << endl;
        counterSum += counter;
        inputSum += input;
        productSum += product;
    }
    cout<<setfill('_')<<setw(45)<<"_"<<endl;
    cout << setfill(' ') << setw(7) << counterSum << setw(16) << inputSum << setw(18) << productSum << endl;
}
于 2014-04-07T23:45:34.193 回答