如何解决如何使用c ++和gnuplot绘制由等式xt= x0 + v0 * t + 1/2 g t ^ 2运动方程描述的自由下落的粒子的运动?
这是我到目前为止记下的代码:
#include <iostream>
#include <string>
int main()
{
int num;
cout<<"Enter number of plots: "<<'\n';
cin>>num;
double x[num],y[num];
double tf,t;
int nr,v0,x0;
cout<<"Enter value of initial speed: "<<'\n';
cin>>v0;
cout<<"Enter value of initial position: "<<'\n';
cin>>x0;
cout<<"Enter value of final time: "<<'\n';
cin>>tf;
nr =0;
t = 0;
while ((nr <= num) && (t <= tf))
{
y[nr] = (1/2 * 9.81 * t * t) + (v0 * t) + x0;
x[nr] = t;
nr++;
t++;
}
gnuplot_one_function ("Position vs Time","linespoints","t","x(t)",x,y,num);
}
[来自评论]
...该图不符合其(预期)表示形式,例如,如果我输入说初始位置10,则该图仍从0开始。同样,对于其他变量,例如要绘制的点数也无法正确表示。
解决方法
如果我输入的初始位置为10,则图形仍从0开始。
至少这些问题:
1/2是零,整数除法
// y[nr] = (1/2 * 9.81 * t * t) + (v0 * t) + x0;
y[nr] = (0.5 * 9.81 * t * t) + (v0 * t) + x0;
// Better to avoid naked constants
// https://en.wikipedia.org/wiki/Standard_gravity
#define STD_GRAVITY (9.80665 /* m/(s*s) */)
// Advanced: more efficient and more numerically stable form:
y[nr] = (0.5 * STD_GRAVITY * t + v0) * t + x0;
索引超出范围
这是未定义的行为(UB)。
将数组从0索引到num-1
,而不是从0索引到num
double x[num],y[num];
...
// while ((nr <= num) && (t <= tf)) {
while ((nr < num) && (t <= tf)) {
y[nr] = ...
...
}
...或double x[num+1],y[num+1];
可变长度数组
C ++中的可变长度数组(VLA)不是标准的。参见Why aren't variable-length arrays part of the C++ standard?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。