0

I am trying to get value for a/b, but I always get '0' for a/b.

Why do I get a/b=0 ?

#include <iostream>
using namespace std;

int main()
{
  int a,b;
  cout << "Give a and b" << endl;
  cin >> a >> b;
  double q=a/b;
  cout << "a/b=" << q;
  return 0;
}
user40
  • 1,361
  • 5
  • 19
  • 34

2 Answers2

2

You are using integer arithmetic, so the division result will be an integer. A floating point value that is between 0 and 1 will get truncated to 0 when interpretted as an integer, before it is assigned to your q variable. So either:

  1. change your a and b variables to double instead of int

  2. typecast a and/or b to double during the division.

Either way, you will then be performing floating-point division instead of integer division, so the result will be a floating-point value.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

Can do double q=double(a)/b; instead.

grigor
  • 1,584
  • 1
  • 13
  • 25