#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
struct SpaceShip
{
int x_coordinate = (rand()%2000) + 1;
int y_coordinate = (rand()%2000) + 1;
};
SpaceShip updateSpaceShip ()
{
SpaceShip ship;
ship.x_coordinate += 100;
ship.y_coordinate +=100;
return ship;
}
int main()
{
SpaceShip ship = updateSpaceShip();
srand(time(NULL));
if ((ship.x_coordinate > 1024 && ship.y_coordinate > 768) || (ship.y_coordinate > 1024 && ship.x_coordinate > 768))
{
cout << "Ship out of range" << endl;
}
else
{
cout << "Ship in range" << endl;
}
return 0;
}
这个问题要求;创建一个太空飞船对象数组,并编写一个程序,不断更新其位置,直到它们全部离开屏幕。假设大小 屏幕是1024像素乘768像素。
我对这一点感到有些困惑。我学习的电子书没有涵盖课程,所以我想我不应该使用它们。我的查询是x和y坐标甚至更新,或者我应该放入while循环或for循环以保持更新。
答案 0 :(得分:0)
假设您不被允许使用构造函数:
struct SpaceShip
{
int x_coordinate;
int y_coordinate;
bool isOnScreen;
};
int main() {
int const NumberOfShips = 10;
int const ScreenWidth = 1024;
int const ScreenHeight = 768;
srand(time(NULL));
SpaceShip Ships[ NumberOfShips ];
for( int i = 0; i < NumberOfShips; ++i ) {
Ships[ i ].x_coordinate = rand() * ScreenWidth / RAND_MAX;
Ships[ i ].y_coordinate = rand() * ScreenHeight / RAND_MAX;
Ships[ i ].isOnScreen = true;
};
int NumberOfShipsOnScreen = NumberOfShips;
while( NumberOfShipsOnScreen > 0 ) {
for( int i = 0; i < NumberOfShips; ++i ) {
if( !Ships[ i ].isOnScreen ) {
continue;
}
Ships[ i ].x_coordinate += 100;
Ships[ i ].y_coordinate += 100;
if( Ships[ i ].x_coordinate > 1024 || Ships[ i ].y_coordinate > 768 ) {
Ships[ i ].isOnScreen = false;
--NumberOfShipsOnScreen;
}
}
}
};
答案 1 :(得分:0)
/*
Create an array of space ship objects and write a program that continually updates their
positions, when ship go off the screen then it reset its position.
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void srand(unsigned int t);
struct Space_ship
{
int x_co_ordinate;
int y_co_ordinate;
};
Space_ship Get_new_ship(Space_ship ship);
Space_ship Update_space_ship(Space_ship ship);
int rand_range(int low, int high);
int main()
{ srand(time(NULL));
Space_ship ship[5];
for(int i=0;i<5;i++)
{
ship[i] = Get_new_ship(ship[i]);
}
while(1)
{
for(int i=0;i<5;i++)
{
ship[i] = Update_space_ship(ship[i]);
}
for(int i=0;i<5;i++)
{
if(ship[i].x_co_ordinate < 1024 && ship[i].y_co_ordinate < 768)
{
cout<<"ship "<<i+1<<" : "<<"x = "<<ship[i].x_co_ordinate<<" , "<<"y = "<<ship[i].y_co_ordinate<<endl<<endl;
}
else
{
cout<<"ship "<<i+1<<" is out of scope "<<endl<<endl;
ship[i] = Get_new_ship(ship[i]);
}
for(int i=0;i<50000000;i++) //delay
{
; // do nothing
}
}
}
return 0;
}
int rand_range(int low, int high)
{
int num ;
while(1)
{
num = rand();
if (num>=low && num<= high)
{
return num;
}
}
}
Space_ship Get_new_ship(Space_ship ship)
{
ship.x_co_ordinate = rand_range(0,1024);
ship.y_co_ordinate = rand_range(0,768);
return ship;
}
Space_ship Update_space_ship(Space_ship ship)
{
ship.x_co_ordinate += 100;
ship.y_co_ordinate += 78;
return ship;
}