C++控制台应用,其中有两个冲突的对象不工作
C++ console app with two colliding objects not Working
#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;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 两个运营商的一些奇怪的冲突<<
- C++控制台应用,其中有两个冲突的对象不工作
- 包括两个文件 C++ 之间的冲突
- 如何解决两个不使用命名空间的第三方库之间的类名冲突?
- 两个提升版本之间的冲突
- GCC 6.3.0 中的 ODR 冲突,类型在两个单独的翻译单元中定义
- 加载具有相同符号的两个共享库时是否存在符号冲突
- 避免与具有相同名称的两个类发生命名空间冲突
- CMake - 两个库中的相同文件名发生冲突
- 将两个字符串一起分配,获取访问读取冲突
- 从两个类继承的类,具有相同的函数原型,彼此冲突
- 当我的程序有两个不同的QGLWidget时,访问冲突
- 两个精灵列表的冲突-SFML2.0
- 检查来自不同类的两个Rect之间的冲突
- 不明确的引用和命名空间(来自两个外部库的定义冲突)