【发布时间】:2020-05-05 20:25:35
【问题描述】:
在我调用 updateStats 后,我的 Stats 结构中包含的所有变量都会不断地自行重置。我没有正确引用或传递我的 Stats 变量吗?不确定要提供哪些其他信息,因为这是我提出的第一个问题,但显然我需要输入更多信息。如果它有帮助,这个程序应该代表了月球着陆器模拟游戏的一个非常基本的版本。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
struct _stats
{
double altitude, velocity, mass, fuel, acceleration;
};
typedef struct _stats Stats;
void printStats(Stats a, double thrust)
{
printf("Thrust: %f Altitude: %f Velocity: %f Mass: %f Fuel: %f\n", thrust, a.altitude, a.velocity, a.mass, a.fuel);
}
void updateStats(Stats a, double thrust, int time)
{
a.acceleration += (thrust / a.mass -1.6) * time;
a.mass -= thrust / 3000.0;
printf("aaaaa%f", a.mass);
a.fuel -= thrust / 3000.0;
a.velocity += a.acceleration * time;
a.altitude += a.velocity * time;
}
double thrustAllowed(Stats a, double thrust)
{
if (thrust/1000 <= 45 && thrust <= (3000 * a.fuel))
{
return thrust;
}
else
return (3000*a.fuel)/1000;
}
int main(void)
{
FILE* inputFile = fopen("simulation.csv", "wt");
if (!inputFile)
{
printf("Unable to open file.\n");
return 1;
}
int time = 0;
double thrust = 0;
Stats rocket;
rocket.altitude = 150000;
rocket.velocity = -325;
rocket.mass = 9000;
rocket.fuel = 1800;
rocket.acceleration = 0;
while (time < 150)
{
time++;
fprintf(inputFile, "Enter a Thrust in kN: ");
scanf("%lf", &thrust);
fprintf(inputFile, "%f", thrust);
thrust = thrust * 1000;
if (thrustAllowed(rocket, thrust) == thrust)
{
updateStats(rocket, thrust, time);
fprintf(inputFile, "\nThrust: %.1f Altitude : %.1f Velocity : %.1f Mass : %.1f Fuel : %.1f\n", thrust, rocket.altitude, rocket.velocity, rocket.mass, rocket.fuel);
if (rocket.altitude <= 0)
{
if (rocket.velocity <= 0 && rocket.velocity >= -1)
{
fprintf(inputFile, "Soft Landing!!!");
break;
}
else
{
fprintf(inputFile, "You broked it");
break;
}
}
}
else
fprintf(inputFile, "Thrust must be <= %.1f\n", thrustAllowed(rocket, thrust));
}
fclose(inputFile);
}'''
【问题讨论】:
-
您是按值传递,而不是按引用传递。修改你的 updateStats 以获取一个指针,或者让它直接修改全局变量而不是使用传入的参数。
-
updatestats正在处理您作为 局部变量的副本传递的内容,因此任何更改都不会反映在原始变量中。 -
@MichaelDorgan 说的是原因,尽管我建议不要使用全局变量。另一种方法是使
updateStats()类型为Stats并返回修改后的a变量。欢迎来到 SO! -
(同意,全局变量是一种不好的方法......)
-
OT:关于:
printf("Unable to open file.\n");错误消息应该输出到stderr,而不是stdout。当错误来自 C 库函数(如 fopen)时,还应输出系统认为发生错误的文本原因。建议调用perror( "Unable to open file.");,因为这将正确执行这两个操作
标签: c