- 5
Why am I not getting correct answer in this code?
#include <stdio.h> int main() { long int length = 2999393000; long int width = 38395959; int area; area = length * width; printf("%d \n", area); /* 50 */ return 0; }
14 Réponses
+ 5
The multiplication result from the two numbers is much too big to fit in the range of `int` type. You can get the result by using an `unsigned long long` type instead.
unsigned long long area = (unsigned long long)length * width;
printf("%llu \n", area);
Notice that:
* Type casting is necessary for either <length> or <width> before they are multiplied.
* %llu specifier (for `unsigned long long` type) is used in place of %d specifier (for `int` type). Use of improper format specifier can cause problems.
P.S. Please use proper tags for the thread. 'wewantjustice' has nothing in relation to the problem.
+ 4
The answer will never be 50 as your multiplying not dividing...
Multiplying will result in a number that is larger than both numbers
+ 4
Vipul Rohit the type of the variable `area` is int. `int` data type is not big enough to hold the value of such big numbers, i.e. the number overflows the int data type. So the value is cut down to fit the data type, which mostly results in gibberish.
To make the code work, change the data type of `area` from `int` to `long`. Also change %d in the printf statement to %ld, to be able to display the long value (%d is for int, %ld is for long).
+ 2
What is the error...
it works fine for me....
https://code.sololearn.com/c6NriYod4Fq5/?ref=app
+ 2
What is the error...
it works fine for me....
https://code.sololearn.com/c6NriYod4Fq5/?ref=app
+ 2
Even when I search for this on googke it shows error.. calculator too shows error....
Maybe length is big
+ 2
I don't know why you used wewantjustice tag .You should use c tag.
By the way, here is the solution:
https://code.sololearn.com/cezxpHSq24E1/#c
+ 2
Vipul Rohit please use correct tags so the community can find your question easier. wewantjustice has no catagories
unlike c, area, length, width, long int
Thanks and happy coding.
0
But still it's telling that coding is wrong. It's not giving any answer
0
I don't know . I just installed this app yesterday. When I compiled,it's told that length is too much.
0
But correct answer for it is
115164570652887000
0
Here u will get correct answer with no error.
https://www.wolframalpha.com/input/?i=2999393000%C3%9738395959
0
Yeah, that website is very powerful
0
//Edited code for correct output
#include <iostream>
using namespace std;
#include <stdio.h>
int main() {
long int length = 2999393000;
long int width = 38395959;
long long int area;
area = length * width;
printf("%lld \n", area);
return 0;
}
//explanation is already provided by others in previous posts..
// by @xxx, and @ipang..