-1

I don't know the reason why the float doesn't print exact value when I execute this program.

#include <iostream>
using namespace std;

int main(){

int a, b;
float x;

cout << "Input the value for a: ";
cin >> a;
cout << "Input the value for b: ";
cin >> b;

x = - b / a;

printf("The value of x is: %.2f",x);
//cout << "The value of x is: " << x;

}

I want to at least when I input 2 for a and 10 for b the result should be 0.20, the program shows 0.00 only

Marr
  • 555
  • 1
  • 6
  • 11

2 Answers2

3

You need to cast your operands as floats.

    ex: x = (float)a / (float)b

Look here for more information:

Dividing two integers to produce a float result

Community
  • 1
  • 1
King Arthur
  • 103
  • 11
0

First of all output you are expecting I think is wrong.

It should be -5.00 -10/2 = -5. and with %.2f => -5.00

Suppose. if a=10 and b= 2, then as per your code

 `x= - 2/10` 

This should give

 x = 0. Notice the `\`.

Since you are printing it with %.2f it gives 0.00 which the system gives.

I hope this clarifies your doubt.

jonju
  • 2,711
  • 1
  • 13
  • 19
  • yes thats the result but what i want to see is the excact answer like 0.20 is there anything should i add to print out the excact value? – Marr Aug 04 '16 at 22:27
  • you can get it with @King Arthur's answer by typecasting to float – jonju Aug 04 '16 at 22:33