why function isnt returning double

Explanation on why the weight is returning back as an integer and not double? thanks.

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
/*Write a program that models a virtual pet. We will assume the pet will have a weight and can be
 in a state of being hungry or not hungry. The pet can be fed which will in turn effect the pet's hunger 
state and according the following:
	1) if the food weight is greater than or equal to one half of the pet's weight, the
 pet will not be hungry, otherwise it will be hungry.
	2) the weight added to the pet will be one quarter of the food weight.*/
#include <iostream>
#include "vPet.h"
using namespace std;

int main(){
	VPet bob(150, false); 
	bob.feedPet(25);

	VPet sam;
	sam.feedPet(10);

	cout <<"Bob weighs: " << bob.getWeight() << endl;
	cout <<"Sam weighs: " << sam.getWeight() << endl;

	if (bob.getHungry())
		cout << "Bob is hungry.";
	else
		cout << "Bob is not hungry.";
	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "vPet.h"

VPet::VPet(int w, bool hun):weight(w),hungry(hun){
}

VPet::VPet():weight(100),hungry(true){
}

void VPet::feedPet(int amt){
	if(amt >= 0.5 * weight)
		hungry = false;
	else{
		hungry = true;
	}
	weight = (double(weight + 0.25 * amt));
}

double VPet::getWeight(){
	return weight;
}

bool VPet::getHungry(){
	return hungry;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef VPET_H_
#define VPET_H_


class VPet{
	public:
	// Constructors (member functions)
	VPet(int weight, bool hungry);
	VPet();

	// member functions
	void feedPet(int amount);
	bool getHungry();
	double getWeight();

	private:
	
	// data members
	double weight;
	bool hungry;
};

#endif /*VPET_*/ 
In your feed pet function try changing
 
weight = (double(weight + 0.25 * amt));


to

 
weight = ((weight + 0.25 * (double)amt));


That will convert amt from an int to a double leaving you with only doubles in your multiplication instead of multiplying by an integer.

If this doesn't work, try changing your constructor
 
VPet(int weight, bool hungry);


To take a double instead of int weight
Topic archived. No new replies allowed.