Я работаю над программой, которая, как предполагается, имеет 3 разных робота, участвующих в гонках на трассе. Трасса должна быть 100 в длину. Я только что узнал наследование и все еще пытаюсь понять, как подключить данные от одного.h к другому. Когда я запускаю свою программу, ничего не происходит, когда я звоню любому из моих Роботов. В качестве примера я покажу один из них. Можете ли вы объяснить, как сделать свои движения обновлением 2D-массива гонки?
robotRace.h
#ifndef ROBOTRACE_H
#define ROBOTRACE_H
using namespace std;
class robotRace {
public:
robotRace (); //constructor
static const int rows = 5;
static const int columns = 100;
protected:
int race[rows][columns]; //initial base for race floor
};// end superclass robotRace that should do no movement
#endif
robotRace.cpp
#include <iostream>
#include "robotRace.h"
using namespace std;
robotRace :: robotRace() {
for (int i = 0; i < rows; i++)
for (int j= 0; j<columns; j++)
race[i][j] = ' ';
}//end constructor
Это один из роботов и их функции для обновления массива. Не знаете, как заставить его работать.
FunctionRobot.h
#ifndef FUNCTIONROBOT_H
#define FUNCTIONROBOT_H
#include "robotRace.h"
using namespace std;
class FunctionRobot : public robotRace{
public:
FunctionRobot();
int position(int);
void print();
protected:
};
#endif
FunctionRobot.cpp
#include <iostream>
#include "FunctionRobot.h"
#include <cmath>
using namespace std;
FunctionRobot :: FunctionRobot (): robotRace() {
int initPos =0;
race[initPos][0] = '*';
cout <<"Initial position of Function Robot is at begin of race."<<endl;
}
int FunctionRobot :: position(int place=0){
// log with a base 2 needs to be divided by the "x"
// below is the Robots formula to determine each of their movements
double x = ( 2 * (log(place)/log(2)));
return (int) x;
}
void FunctionRobot :: print(){
for (int i;i=0; i<100; i++)
for (int j;j=0; j<1; j++)
race[position()][j];
}
это мой основной файл в соответствии с запросом. Это основной формат. Я надеюсь, что цикл while будет более практичным, так что пользователю не нужно будет вводить 1. Также нет ошибки, исходящей из моего кода. Он работает только ничего не показывает.
main.cpp
#include <iostream>
#include "robotRace.h"
#include "FunctionRobot.h"
using namespace std;
int main() {
int userInput;
cout << "Welcome to the Robot Race of the year!" << endl;
cout << "For our contestants we have the amazing three!" << endl;
cout << "The contestants are Robots F, R and U" << endl;
cout << "Let the games begin! \n\n";
cout << "Enter 1 to begin. " << endl;
cin >> userInput;
FunctionRobot functionObj;
//functionObj.position();
//functionObj.print();
cout << "Ready... Set... Go!!" << endl;
while (userInput == 1) {
functionObj.position(4);
functionObj.print();
} //end while
return 0;
}
Ваш print()
выходит за пределы:
void FunctionRobot :: print(){
for (int i; i<100; i++)
for (int j; j<1; j++)
race[position()][j];
}
j
не инициализируется. Вы можете попробовать int j = 0
для начала. Аналогично для i
.
Кроме того, вы знаете, что эта функция называется PRINT, но не ПЕЧАТЬ НИЧЕГО, на самом деле она ничего не делает, кроме вызова position()
.
int FunctionRobot :: position(int place=0){
// log with a base 2 needs to be divided by the "x"
// below is the Robots formula to determine each of their movements
double x = ( 2 * (log(place)/log(2))); <-------- now x is a double
return (int) x; <-------- now x is an integer, are you sure about that?
}
Здесь происходит потеря точности. Пусть говорят, что x
присваивается значение 3.14. Затем вы выполняете его (приведение происходит автоматически, так как возвращаемый тип функции также является int) в целое число, поэтому оно будет преобразовано в 3, таким образом, вы потеряете точность.
О main.cpp
Вы вызываете пользователя для ввода 1, а затем у вас есть:
while (userInput == 1) {
functionObj.position(4);
functionObj.print();
} //end while
но userInput
не будет изменен, поэтому вы работаете в бесконечном цикле.