我用C ++构建一个小型物理引擎,用户在一组发射参数上发射一个射弹(高度,角度,时间间隔和初始速度),然后显示一些信息,如总距离或它在空中的每个时间间隔的角度,直到它撞到地面。这样你就可以看到,这是我的计划:
cout << "Insert a lanuch Angle (theta): ";
cin >> thetaDegrees;
cout << "Insert a launch height: ";
cin >> yOld;
cout << "Insert an initial velocity: ";
cin >> initialVelocity;
cout << "Time (DeltaT) in seconds: ";
cin >> totalT;
for (double deltaTime = 0.0; deltaTime < totalT; deltaTime += 0.1) {
const double squared = deltaTime * deltaTime; // squared constant for deltaTime squared
theta = thetaDegrees * PI / 180; // converts theta to a degrees value
velocityX = initialVelocity * cos(theta); // calculates Vx
velocityY = initialVelocity * sin(theta); // calculates Vy
// apply initialV to velocity
velocity = initialVelocity + 9.8 * time;
xNew = xOld + velocity * time; // works out displacement for X
yNew = yOld + velocity * deltaTime - gravitiyHalf / 0.5 * (squared); // calculates Y
velocityY = velocity - 9.8 * deltaTime; // includes gravity to Y
angle = atan2(yNew, xNew) * 180 / PI; // convert angle to degrees
cout << "\nHeight: " << yNew << endl;
cout << "Distance in Meters: " << xNew << "m" << endl;
cout << "Angle: " << angle << endl;
cout << "Time: " << deltaTime << "s " << endl;
if (heightCheck == false) {
maxHeight = yOld;
// keep maxheight equal to previous height
}
if (yNew < yOld && heightCheck == false) {
heightCheck = true;
// if projectile is going down, trigger maxheight
}
cout << "Maximum height: " << maxHeight << endl;
if ((yNew < 0) || (deltaTime == totalT)) {
getchar(); // stops if delta t = total T or projectile landed
}
yOld = yNew; // refresh x & y
xOld = xNew;
}
在我的课程简介中,我告诉了以下内容:
软件必须能够输出两个平面文件,以便检查您的工作
所以我需要能够将我的程序输出到文件,这是什么意思,我该怎么做?
答案 0 :(得分:1)
查看fstream库,这是执行文件输入和输出的C ++标准方法。更具体地说,请查看创建文件std::fstream out( "output.txt", std::fstream::out )
,并写入文件std::string word = "some text"; out << word;
。
使用fstream,您可以将任何基本类型写入文件,因此您可以使用out << number
编写普通数字(固定或浮点数),并且它与std::cout
的效果相同。< / p>