练习了一些 C++,我从一本书中遇到了一些代码。对我来说,使用带有 break 接缝的 if 语句有点不必要:
if (!(cin >> dstep)) 中断;
这对我来说有点骇人听闻,只需使用没有 if 或 break 的 cin >> dstep 即可正常运行程序。有什么想法吗?
int main()
{
using namespace VECTOR;
srand(time(0)); //seed random-number generator
double direction;
Vector step; //creates default object
Vector result(0.0, 0.0); //
unsigned long steps = 0;
double target;
double dstep;
cout << "Enter target distance (q to quit): ";
while (cin >> target)
{
cout << "Enter step length: ";
if (!(cin >> dstep)) //if NOT inputing into dstep THEN break/means if INPUTING is TRUE, keep going and don't break out of loop
break;
//cin >> dstep // why not just use this?
while (result.magval() < target)
{
direction = rand() % 360;
step.set(dstep, direction, 'p'); //sets the values dstep and direction based on the form; in this case 'p'
result = result + step;
steps++;
}
cout << "After " << steps << " steps, the subject "
"has the following location:\n";
cout << result << endl;
result.polar_mode();
cout << " or\n" << result << endl;
cout << "Average outward distance per step = "
<< result.magval() / steps << endl;
steps = 0;
result.set(0.0, 0.0);
cout << "Enter target distance (q to quit): ";
}
cout << "Bye!\n";
cin.get();
return 0;
}