我正在进行“随机漫步”计划,我无法正确显示这些条形图。
这是我的代码(我只会包含我需要帮助的内容):
#include <iostream>
#include <conio.h>
#include <string>
#include <ctime>
#include <random>
using namespace std;
int main() {
srand(time(0)); // make it "random"
int max;
int min;
int location; //location of goat on bridge
int steps;
int total_steps;
int choice;
int move; // go forward or backward
for (;;) { // Keep running until user quits
system("CLS");
cout << "Random Walk Simulator" << endl;
cout << "1) Display Trial " << endl;
cout << "2) Run Statistics Over 50 Trials " << endl;
cout << "3) Quit. " << endl;
cin >> choice; // get choice
cout << "\n";
if (choice == 1) { // Display Trial
steps = 1;
location = 4; // center of bridge
cout << "Step 0: | * | " << endl;
while (location >= 1 && location <= 7) { // Keep running until goat falls off bridge
move = rand() % 2 + 0; // 0 and 1
if (move == 0) { // Move backward
location--;
}
if (move == 1) { // Move forward
location++;
}
switch (location) { // Show location
case 0: cout << "Step " << steps << ": | | " << endl;
break;
case 1: cout << "Step " << steps << ": |* | " << endl;
break;
case 2: cout << "Step " << steps << ": | * | " << endl;
break;
case 3: cout << "Step " << steps << ": | * | " << endl;
break;
case 4: cout << "Step " << steps << ": | * | " << endl;
break;
case 5: cout << "Step " << steps << ": | * | " << endl;
break;
case 6: cout << "Step " << steps << ": | * | " << endl;
break;
case 7: cout << "Step " << steps << ": | *| " << endl;
break;
case 8: cout << "Step " << steps << ": | | " << endl;
break;
default: break;
}
steps++; // Iterate steps
}
cout << "\nTotal steps taken: " << (steps - 1) << endl; // (steps-1) since I start the goat off at the center of the bridge
system("PAUSE");
}
以下是示例输出:
Random Walk Simulator
1) Display Trial
2) Run Statistics over 50 Trials
3) Quit
1
Step 0: | * |
Step 1: | * |
Step 2: | * |
Step 3: | * |
Step 4: | * |
Step 5: | * |
Step 6: | * |
Step 7: | * |
Step 8: | * |
Step 9: | * |
Step 10: | * |
Step 11: | * |
Step 12: | * |
Step 13: |* |
Step 14: | |
如何正确格式化?我很擅长C ++,抱歉。
答案 0 :(得分:2)
我只想使用一个标签。在你的行看起来像这样:
cout << "Step " << steps << ": | | " << endl;
将其更改为:
cout << "Step " << steps << ":\t| | " << endl;
答案 1 :(得分:2)
尝试使用setw()
setw reference
所以你的cout
应该看起来像
cout<<std::setw(9);
cout << "Step " << steps;
cout<<std::setw(0);
cout<<: "| *|";
答案 2 :(得分:2)
您需要添加额外的I/O manipulators来正确格式化输出。
只需替换
<< steps
使用以下代码
<< right << setw(2) << steps
那些case
块中的
case 0: cout << "Step " << steps << ": | | " << endl;
setw(2)
将输出字段宽度设置为2,而right
则指示对齐右边框的字段。因此,您的输出看起来像
...
Step 8: | * |
Step 9: | * |
Step 10: | * |
Step 11: | * |
...
您还需要#include <iomanip>
。