Skip to content

Commit c2cb165

Browse files
committed
Update randwalk.cpp
1 parent 0df13cf commit c2cb165

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

ch11/11_1/randwalk.cpp

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@ int main()
2020
// write to file
2121
ofstream fout;
2222
fout.open("walk.txt");
23-
23+
if (!fout.is_open()) {
24+
cout << "Could not write to file \n";
25+
cout << "Program terminating.\n";
26+
exit(EXIT_FAILURE);
27+
}
2428
cout << "Enter target distance (q to quit): ";
2529
while (cin >> target)
2630
{
@@ -29,29 +33,37 @@ int main()
2933
break;
3034

3135
// write to file
32-
fout << "Target Distance: " << target << ", ";
33-
fout << "Step Size: " << dstep << endl;
3436

37+
fout << "Target Distance: " << target << ", Step Size: " << dstep << endl
38+
<< steps << ": " << result << endl;
3539
while (result.magval() < target)
3640
{
3741
direction = rand() % 360;
3842
step.reset(dstep, direction, Vector::POL);
3943
result = result + step;
40-
fout << steps << ": " << result << endl;
4144
steps++;
45+
fout << steps << ": " << result << endl;
4246
}
4347
cout << "After " << steps << " steps, the subject "
4448
"has the following location:\n";
4549
cout << result << endl;
50+
fout << "After " << steps
51+
<< " steps, the subject "
52+
"has the following location:\n" << result << endl;
4653
result.polar_mode();
4754
cout << " or\n" << result << endl;
4855
cout << "Average outward distance per step = "
49-
<< result.magval()/steps << endl;
56+
<< result.magval()/steps << endl;
57+
fout << " or\n"
58+
<< result << endl
59+
<< "Average outward distance per step = " << result.magval() / steps
60+
<< endl;
5061
steps = 0;
5162
result.reset(0.0, 0.0);
5263
cout << "Enter target distance (q to quit): ";
5364
}
5465
cout << "Bye!\n";
66+
fout.close();
5567

5668
return 0;
5769
}

0 commit comments

Comments
 (0)