1

I tried a lot of methods:

float a = 1234.34;
float b = 1234.52;
float r = a * b;
cout << r << endl;
float c = 1234.34 * 1234.52;
cout << c << endl;

cout << 1234.34 * 1234.52 << endl;
cout << (float)(1234.34 * 1234.52) << endl;

And all of these seem to be giving an infinite values..

1.52382e+006
1.52382e+006
1.52382e+006
1.52382e+006

What am I doing wrong here?

  • 4
    None of those seem to be giving an infinite values [sic]. Perhaps you're simply not familiar with the [E notation](http://en.wikipedia.org/wiki/Scientific_notation#E_notation) – eerorika May 19 '14 at 14:00
  • 1
    That's not an infinite value. It's the floating-point representation of the product you're multiplying. Your code is working fine. – Bucket May 19 '14 at 14:00
  • Your definition of infinite seems quite small. You are multiplying two numbers that are about 1,000 times each other. The answer should be around 1,000,000. 1.52382e6 is the same as 1.52382*10^6, which is 1.5 million. Seems like the computer works. – mtrw May 19 '14 at 14:01
  • http://stackoverflow.com/questions/6301547/turn-off-scientific-notation-on-float – Joachim Isaksson May 19 '14 at 14:02

5 Answers5

6

The number in the result is nowhere close to approaching infinity.

The result is simply C++ showing the value in scientific notation.

Please check How to avoid scientific notation for large numbers?.

Community
  • 1
  • 1
jordan
  • 959
  • 7
  • 17
3

The values are not infinite, they're only in scientific notation.

1.52382e+006 evaluates to 1.52382 * (10)^6.

You may want to use doubles, and set the precision for the ostream:

#include <limits>    // std::numeric_limits
#include <iostream>  // std::cout

int main() {
  double f = 3.141592;

  std::cout.precision(std::numeric_limits<double>::digits10);
  std::cout << std::fixed;
  std::cout << f;

  return 0;
}
2

The answer is correct. 1.52382e+006 is same as 1.52382 * 106

If you don't want the output in E format, use std::fixed

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    float a = 1234.34;
    float b = 1234.52;
    float r = a * b;
    cout << std::fixed << r << endl;
    float c = 1234.34 * 1234.52;
    cout << std::fixed << c << endl;

    cout << std::fixed << 1234.34 * 1234.52 << endl;
    cout << std::fixed << (float)(1234.34 * 1234.52) << endl;
    return 0;
}

This code outputs the following

1523817.375000
1523817.375000
1523817.416800
1523817.375000

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
1

What you get is the scientific notation of your results, 1523817.4168, which in in scientific notation is 1.52382E+6, where the E stands for "10^", meaning 1.52382 * 10 ^ 6, you can look it up.

private_meta
  • 561
  • 4
  • 19
1

That is just scientific notation. It does not signify infinity.

Benjamin Trent
  • 7,378
  • 3
  • 31
  • 41