siratahmed139's blog

By siratahmed139, history, 3 years ago, In English

What is the difference between these two codes?? ==================cout<<pow(10,a-1)+pow(10,c-1)<<" "<<pow(10,b-1)

And int a;int b; a=pow(10,a-1)+pow(10,c-1); b=pow(10,b-1); cout<<a<<" "<<b

update :I am newbie,was this the reason for getting so many down votes??

  • Vote: I like it
  • +8
  • Vote: I do not like it

| Write comment?
»
3 years ago, # |
Rev. 2   Vote: I like it +14 Vote: I do not like it

cout<<pow(10,x); would print the power of the numbers in double.

Hence when the values get higher then the values are curbed to their scientific notation .

cout<<pow(10,7); may be 1e+007.

But in the second method , as you are assigning the power to an integer, the double will be implicitly converted to int to give 10000000 .

Caution: The result may have precision errors when typecasting as we are downcasting from double to int .

Hence pow(10,7) may also be 9999999.

So it is recommended to use Custom power function or Binary Exponentation.

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This looks like the "Corporate wants you to find the difference between these two pictures" meme template ;)

Anyway, the difference here is that

int b = pow(10, b-1);

casts $$$10^{b-1}$$$ to an integer, because pow returns a double. Same for a. iirc this problem wanted integer output. It works fine with smaller numbers, because 100.0 is printed as 100. However, $$$10^9$$$ is printed as 1e+09, which the grader cannot understand. When you cast it to an integer, it gets printed out like you would expect.

If you really want to make that code work by still outputting decimals, you can do the following:

cout << fixed << setprecision(0);

which means there will be no numbers outputted after the decimal point.
See my submission (although I use cout.precision(0); instead of cout << setprecision(0);)

Also, it doesn't affect this problem, but whenever you use floating-point (decimal) numbers, beware of precision errors.