0

In my code I can't get the right division I don't know why

I have for example ;

int N =5;
int df = 2;
double value = N/df;

when I use the previous code I get the value = 2 , I need return 2.5

AYKHO
  • 516
  • 1
  • 7
  • 20

4 Answers4

3

You can convert one of the arguments to double:

  int N = 5;
  int df = 2;
  double value = ((double)N)/df;

or you can initially declare N and/or df as Double

  double N = 5;
  double df = 2;
  double value = N/df;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Sorry, but it does work since I explicitly declare N and df as double. You have to add ".0" in expressions like this: 5.0 / 2.0 which could be ambiguous (5 - integer, 5.0 - double) – Dmitry Bychenko Jul 01 '13 at 09:45
  • Sorry Dimitry, it does work. I had something else in my mind. – FeliceM Jul 01 '13 at 09:56
1

An int divided another int gives you an int. One of the two should be a double. This will work:

double N =5.0;
double df = 2.0;
double value = N/df;

This will work:

double N =5;
int df = 2;
double value = N/df;
FeliceM
  • 4,163
  • 9
  • 48
  • 75
0

Also you can add any double value to calculations

double N =5;
double df = 2;
double value = N*1.0/df;
E-Max
  • 401
  • 5
  • 14
0
try this......

int N =5;
int df = 2;
double value = (double) N/df;
Bala
  • 26
  • 1