C++控制台应用,其中有两个冲突的对象不工作

C++ console app with two colliding objects not Working

本文关键字:冲突 两个 对象 工作 应用 控制台 C++      更新时间:2023-10-16
#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
struct spaceship { // create the ship
int x, y;
char callsign[51];
};
void shiprandloc(spaceship *ship, int maxrange) { //randomize location
ship->x = rand() % maxrange;
ship->y = rand() % maxrange;
}
int shipdetcol(spaceship *ship1, spaceship *ship2, float colrange) { //if they collide return a 1
colrange < 10;
return 1;
}
int main()
{
int maxloc = 100, maxcol = 10;
int numloops;
cout << "Enter the Number of Collisions to Simulate: ";
cin >> numloops;
for (int i = 0; i < numloops; i++) {
int loopcnt = 0;
spaceship *ship1, *ship2;
ship1 = new spaceship;
ship2 = new spaceship;
strcpy_s(ship1->callsign, "Red1");
strcpy_s(ship2->callsign, "Blue1");
shiprandloc(ship1, maxloc);
shiprandloc(ship2, maxloc);
d = sqrt((ship1->x - ship2->x)*(ship1->y - ship2->y)); //find distance between the two ships.
while (!shipdetcol(ship1, ship2, maxcol)) {
++loopcnt;
}
delete ship1, ship2;
}
return 0;
}

用于检查距离的平方根函数不起作用,如果碰撞命中,则返回 1,如果未命中,则返回 0。我错过了什么? .

人类想象中的野兽

delete ship1, ship2;

删除ship2,但不删除ship1。这里的逗号被视为序列(逗号(运算符,并且此类表达式的结果是最后一个子表达式的结果。

您的函数始终返回 1。你可能的意思是这样的

int shipdetcol(spaceship &ship1, spaceship &ship2, float colrange) 
{
return  colrange > sqrt(abs(((ship1.x - ship2.x)*(ship1.y - ship2.y)));
}

请注意,您需要坐标之间差值的绝对值。

最后,它C++,所以不要使用:

#include <string.h>
#include <math.h>

#include <cstring>
#include <cmath>

不要使用

char callsign[51];    

#include <string>

std::string callsign;

现在您可以执行以下操作:

ship1 = new spaceship { 0, 0, "Red1"};
sqrt((ship1->x - ship2->x)*(ship1->y - ship2->y));

您的 sqrt 将尝试取一个数字的平方根,但如果为负,将导致发生域错误。因此,您应该检查是否有任何减法导致负数,因为它也可能使乘法结果为负数,从而弄乱结果。

在这里:

colrange < 10;
return 1;

您的代码没有检查IF列范围小于 10,它只是在编写一个表达式。它应该是:

if(colrange<10){
return 1;
}
else
{
return 0;
}