因此,以下代码可以正常工作,但有一个例外:

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


int main()
{
    int value1, value2, value3, value4;
    float calcMean,calcStDev;


    // Input values from keyboard
        // prompt user for input
    cout << "Enter 1st value. " << endl;
    cin >> value1;
    cout << "Enter 2nd value. " << endl;
    cin >> value2;
    cout << "Enter 3rd value. " << endl;
    cin >> value3;
    cout << "Enter 4th value. " << endl;
    cin >> value4;

    // Calculate the mean, mean = (value1 + value2 + value3 + value4)/4.0
    calcMean = (value1 + value2 + value3 + value4) / 4.0;

    // Calculate the standard deviation, standard deviation = squareroot((sum((input value-mean)*(input value-mean)))/number of input value - 1)
    calcStDev = sqrt((pow((value1 - calcMean),2) + pow((value2 - calcMean),2) + pow((value3 - calcMean),2) + pow((value4 - calcMean),2))/(4-1));
        // Output display
    cout << fixed << setprecision(2) << endl;
    cout << "Mean of the four values:               " << setw(10) << calcMean << endl;
    cout << "Standard deviation of the four values: " << setw(10) << calcStDev << endl;

    cin.get();
    cin.get();
    return 0;
}


输出似乎没有像我期望的那样响应setw()(我希望数字18.50直接在19.64之上,一个在另一个之上)。

知道我在做什么错吗?:

Enter 1st value.
2
Enter 2nd value.
36
Enter 3rd value.
35
Enter 4th value.
1

Mean of the four values:                                     18.50
Standard deviation of the four values:      19.64

最佳答案

我认为问题在于字符串文字"Mean of the four values: "包含嵌入的制表符。要插入空格,可以按TAB键而不是SPACEBAR键。

关于c++ - C++中的Setw()没有像我预期的那样响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21646354/

10-10 07:13