division error

Hi, I am new in C++

Why the output = 6 and not 6.5?
What I do wrong?
Thank you for your answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// error division in C++
#include <iostream>
using namespace std;
int main ()
{
// initialize variables	
int a=13, b=2;
float c;							
c=a/b;
cout << endl;
cout << "c = " << c;
cout << endl;
return 0;
}
Last edited on
Any integer number can be represented as

a = c * b + r;

where r is the remainder. It is so-called arithmetic mathematics. In you case you have

13 = 6 * 2 + 1;

where a = 13, b = 2, and c = 6

If you will write c = a % b;

when you will get the reminder r that is equal to 1.
Last edited on
With int a=13, b=2;

The expression a/b results in integer division. 13/2 == 6

a / double(b) or double(a) / b would result in floating point division. 13.0 / 2.0 == 6.5 (approximate)
Thank you all :)
You can obtain floating-point by float/int not int/int you have to change your variables 'a' and/or 'b' to float or do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using std::cout;
using std::endl;

int main(){

int b=13;
int a=2;

float c;

c=static_cast<float>(b)/a; //create a temporary floating-point copy of its operand in parentheses 'b'

cout<<"C= "<<c<<endl;

return 0; //indicate successful termination
}//end main
Topic archived. No new replies allowed.