Classes trouble :S

Hey.
I'm having trouble with getting classes down, some help would be great!
I wrote a very simply program that just calculates the average travel time of a vehicle using the formula "t= d/v"
The program compiles fine but when i try to do the calculation it gives me funny answers. For instance, i type in speed = 5 and distance = 10 and it outputs the time to be 1 second.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <cstdlib>
#include <iostream>
#include <math.h>

using namespace std;

class travelTime {
        int a;
        int b;
    public:
        void data(int, int);
        int tTime() {
            int result = 0;
            result = b/a;
            return result;
        }
};

void travelTime::data(int speed, int distance) {
    speed = a;
    distance = b;
}

int main(int argc, char *argv[])
{

    int speed2 = 0, distance2 = 0;
    cout << "please type in the distance and speed of a sportscar: ";
    cin >> speed2;
    cin >> distance2;
    cout << "\n";
    travelTime tT;
    tT.data(speed2, distance2);
    cout << "\n the travel time of the sportscar is: " << tT.tTime() << "seconds \n";
    return 0;
    
}


NOTE: Yes i know that this can be done with half the effort without using classes but the idea is just to get a basic understanding of classes and how to use them :)

Thanks in advance!
jPytlo
Last edited on
1
2
3
4
void travelTime::data(int speed, int distance) {
    speed = a;
    distance = b;
}


Your assignments are backwards. You're assigning uninitialized a and b to temporary speed and distance. You probably want to do it the other way around.
you sir are a gentleman and a scholar
Topic archived. No new replies allowed.