c++ - 具有两个碰撞对象的 C++ 控制台应用程序不起作用
问题描述
#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,如果它未命中则返回 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"};
推荐阅读
- algorithm - 如何找到两个素数 p 和 q,其中 p 和 q 足够大并且 q 整除 p - 1?
- python - 按值对python中的嵌套字典进行排序
- elixir - Elixir - 更新具有字符串键的地图
- c# - C++ 指针与 C# 指针
- angular-material - 垫子扩展面板在垫子选项卡中无法正常工作
- amazon-redshift - Amazon Redshift - 清理和分析详细信息
- python-3.x - 如何允许用户从python中唯一随机数的6x6矩阵中选择一个随机数?
- react-native - react-native [ios] native-base picker TypeError:无法读取未定义的属性“值”
- c# - 使用 ItemAppearing 事件在 ListView 中向下滚动跳过 Xamarin.Forms 中的记录
- c# - 位图中的 C# 图像以定位 XY