如何使用 setw() 使第一个数字始终对齐

问题描述 投票:0回答:2

这是我的代码中需要修复的部分:

    for (int i=0; i<=time; i++) { // time is a variable defined earlier in my code
        distance = 0.5 * 9.8 * (i*i); // distance was also earlier defined
        cout << i << setw(27) << distance << endl; //what I'm trying to fix
    }

这是我的输出:

这就是我想要的样子:

c++
2个回答
0
投票

由于您似乎希望两列之间具有固定大小,因此您可以简单地执行以下操作:

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    std::string spaces (27, ' ');
    
    int time = 3;
    for (int i=0; i<=time; i++) 
    {
        double distance = 0.5 * 9.8 * (i*i);
        std::cout << i << spaces << distance << "\n";
    }
}

演示


0
投票

您的问题与文本对齐有关,此代码应该可以帮助您解决它


#include <iostream>
#include <iomanip>  // Include iomanip for setw, left, right
using namespace std;

int main() {
    // Example 'time' variable
    int time = 5;

    // Print the headers first
    cout << left << setw(20) << "Time Falling (seconds)" << setw(30) << "Distance Fallen (meters)" << endl;
    cout << "*******************************************" << endl;

    for (int i = 0; i <= time; i++) {  // Loop over time
        double distance = 0.5 * 9.8 * (i * i);  // Calculate distance fallen
        cout << left << setw(20) << i << setw(30) << distance << endl;  // Left-align both columns
    }

    return 0;
}

© www.soinside.com 2019 - 2024. All rights reserved.