C++返回值显示为-858993460

C++ return value showing -858993460

本文关键字:-858993460 显示 返回值 C++      更新时间:2023-10-16

我是c++的新手,正在尝试创建一个汽车类程序,询问用户一年的时间和汽车的品牌。然后程序获取速度,该速度始终从0开始,加速5英里/小时5次,制动5英里/时5次。我必须创建一个带有头文件和两个cpp文件的程序。速度的返回值不正确,显示为:

输入汽车年份:2000输入汽车品牌:雪佛兰起始速度为-885993460

当前速度为:-885993455英里/小时。

当前速度为:-885993450英里/小时。

当前速度为:-885993445英里/小时。

当前速度为:-885993440英里/小时。

当前速度为:-858993435英里/小时。

当前速度为:-885993440英里/小时。

当前速度为:-885993445英里/小时。

当前速度为:-885993450英里/小时。

当前速度为:-885993455英里/小时。

当前速度为:-858993460英里/小时。

按任意键继续。

有人能帮我弄清楚我做错了什么吗?到目前为止,我已经附上了我所拥有的。非常感谢您的帮助。感谢

#define CAR_H
#include <string>
using namespace std;
class Car 
{
   private:
        int yearModel;
        string make;
        int speed;
    public:
        Car(int, string);
    void accelerate();
        void brake();
       int getSpeed ();
};
#include <iostream>
#include "Car.h"
using namespace std;
Car::Car(int carYearModel, string carMake)
{
    int yearModel = carYearModel;
    string make = carMake;
int speed = 0;
}
void Car::accelerate()
{
    speed += 5;
}
void Car::brake()
{
    speed -= 5;
}
int Car::getSpeed()
{
    return speed;
}
int getYear(int year)
{
    return year;
}
string getMake(string make)
{
return make;
}
#include "Car.h"
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
    int count;
int yr;
string mk;
int getSpeed;
cout << "Enter the year of the car: ";
cin >> yr;
cout << "Enter the make of the car: ";
cin >> mk;
Car myCar(yr, mk);
    cout << "The starting speed is "  
    <<  myCar.getSpeed() << endl << endl;
    for ( count = 0; count < 5; count++)
    {
        myCar.accelerate();
        cout << "The current speed is: " << myCar.getSpeed() 
        << " mph." << endl;
    } 
    for ( count = 0; count < 5; count++)
    {
        myCar.brake();
        cout << "The current speed is: " << myCar.getSpeed() 
        << " mph." << endl;
    }
    system ("pause");
    return 0;
}

在此代码中:

 Car::Car(int carYearModel, string carMake)
 {
      int yearModel = carYearModel;
      string make = carMake;
      int speed = 0;
 }

您没有指定给Car对象的数据成员。相反,您使用与字段相同的名称声明局部变量,然后为这些局部变量赋值。

要解决此问题,请删除以下类型:

 Car::Car(int carYearModel, string carMake)
 {
      yearModel = carYearModel;
      make = carMake;
      speed = 0;
 }

希望这能有所帮助!