我是C ++的新手,目前正在编写一个模拟固定数量的粒子在盒子中传播的程序(目前还没有碰撞,这意味着它们理论上应该具有相同的坐标)。但是,我目前在使用数组时遇到问题。在这种情况下,如何初始化,引用,存储数据并输出它们?
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
int main(void) {
float dlvelox;
float dlveloy;
float lvelox[1000];
float lveloy[1000];
float xcord[1000];
float ycord[1000];
float length;
float breadth;
int id;
int stepcount;
int step = 0;
/* Obtaining velocity */
{
printf("Enter the initial h velocity of the ball:\n");
scanf("%f", &dlvelox);
printf("Enter the initial v velocity of the ball:\n");
scanf("%f", &dlveloy);
std::fill_n(lvelox, dlvelox, -1);
std::fill_n(lveloy, dlveloy, -1);
}
/* Initializing box */
{
printf("Enter the length of box:\n");
scanf("%f", &length);
printf("Enter the breadth of box:\n");
scanf("%f", &breadth);
}
/* Obtain number of steps */
{
printf("Enter the number of steps wanted:\n");
scanf("%d", &stepcount);
}
/* Initial console display */
{
printf("\n");
printf("xcord, ycord, step\n");
printf("\n");
}
/* Loop method */
while ( step < stepcount )
for(id = 0; id < 1000; id++)
{
lveloy[id] = lveloy[id] - 9.81;
xcord[id] = xcord[id] + lvelox[id];
ycord[id] = ycord[id] + lveloy[id];
printf("%f, %f, %d\n", xcord[id], ycord[id], step);
if ( ycord[id] < 0 )
{
lveloy[id] = (lveloy[id] * -1);
xcord[id] = xcord[id] + lvelox[id];
ycord[id] = ycord[id] + lveloy[id];
printf("%f, %f, %d\n", xcord[id], ycord[id], step);
}
if ( ycord[id] > breadth )
{
lveloy[id] = (lveloy[id] * -1);
xcord[id] = xcord[id] + lvelox[id];
ycord[id] = ycord[id] + lveloy[id];
printf("%f, %f, %d\n", xcord[id], ycord[id], step);
}
if ( xcord[id] < 0 )
{
lvelox[id] = (lvelox[id] * -1);
xcord[id] = xcord[id] + lvelox[id];
ycord[id] = ycord[id] + lveloy[id];
printf("%f, %f, %d\n", xcord[id], ycord[id], step);
}
if ( xcord[id] > length )
{
lvelox[id] = (lvelox[id] * -1);
xcord[id] = xcord[id] + lvelox[id];
ycord[id] = ycord[id] + lveloy[id];
printf("%f, %f, %d\n", xcord[id], ycord[id], step);
}
step = step + 1;
}
if ( step == stepcount )
{
return 0;
}
}
答案 0 :(得分:1)
使用此行
std::fill_n(lvelox, dlvelox, -1);
您初始化dlvelox
数组中的lvelox
条目数。
但是你循环
for(id = 0; id < 1000; id++)
使用未初始化的数组中的条目。数组中未初始化的条目包含不确定的值,不能用于导致未定义的行为。