Im writing a program that creates matrices and what not then count different things based on the elements in the matrix. That all works fine except 1 part, dividing 2 specific numbers. What htis is for isint important because everything works fine EXCEPT that one part. Anyway, im supposed to calculate Km = t2/m, t2 = 15, r = 21. Km is double, t2 and r are both int. At first i though the problem was that t2 and r were both int,but even when i just write "Km = 16/21" it gives me Km = 0. The thing is i calculate a lot of other divisions but this is the only one thats giving me a problem.

here is the part of the code even though i doubt it'll be a of much use. Knk and Krk all work fine its just that Km thats giving me problems

Knk = t5/r;
	Km = t2/m;
	Krk = 2*t6/(t3*(t3 - 1));
	cout<<"t5 = "<<t5<<endl;
	cout<<"t6 = "<<t6<<endl;
	cout<<"Km = "<<Km<<endl;

>> At first i though the problem was that t2 and r were both int,but even when i just write "Km = 16/21" it gives me Km = 0.


You've hit the nail on the head I think. That's the problem. 16 / 21 is 0. How can it be anything but that? An integer can store 0 or 1. It can't store .7619.

If you do this...

double a = 16 / 21;

a is going to store 0. Why, because what then compiler does is this...

int temp = 16 / 21;
double a = temp;

Do this on the other hand...

double a = 16 / 21.0;

and you're fine.

You can also do this...

int a = 16;
int b = 21;
double c = a / (double) b;

Don't do this...

int a = 16;
int b = 21;
double c = a / b;
commented: Saved my project +0

But i still dont understand why the other divisions work but this one doesnt.

If Knk is a double and t5 and r are both ints, I can't imagine this will work...

Knk = t5/r;

Any calculation or intermediate calculation where the compiler assumed you wanted integer casting when you really wanted floating point will be problematic.

int / int = int
int / double = double
double / int = double
double / double = double

More complex, I'm pretty sure...

int / int / double is the same as (int / int) / double

so you could lose precision. You could also lose precision and it didn't matter (i.e. 2.5 loses precision, 2.0 doesn't).

So go through your statements and see if that's the only place things accidentally get typecast. Fix it by typecasting and see if that changes things. Note that stuff like this won't work...

double a = (double) (16 / 21); // too late!
double b = ((double) 16) / 21; // better

Thank you very much for the help

You're welcome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.