【问题标题】:Setw() in C++ isn't responding as I expectedC++ 中的 Setw() 没有像我预期的那样响应
【发布时间】:2014-02-08 13:08:22
【问题描述】:

所以下面的代码可以正常工作,但有一个例外:

#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

【问题讨论】:

  • 在这里,g++ 4.8.1 和 clang 3.4 都可以。
  • 请记录您使用的文本编辑器,我们要避免使用这种令人难以置信的邪恶。
  • @Hans Passant 例如 MS VS 代码编辑器。:)

标签: c++ formatting setw


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2013-04-11
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多