这是我的代码中需要修复的部分:
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
}
这是我的输出:
这就是我想要的样子:
由于您似乎希望两列之间具有固定大小,因此您可以简单地执行以下操作:
#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";
}
}
您的问题与文本对齐有关,此代码应该可以帮助您解决它
#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;
}