首页 > 解决方案 > 具有两个碰撞对象的 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。我错过了什么?.

标签: c++collisionmath.h

解决方案


这种人类想象力的野兽

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"};

推荐阅读