Reputation: 1
When I enter large numbers like 3,000,000,000 (without commas), I don't get the right result. The number shown is not larger than 9 digits no matter how big a number I input.
The question is as follows:
Perform the following calculation, where the system only accepts positive integers from
0
to3x109
(i.e.3,000,000,000
), and shows the results as a VDU output:y = 3x2 - 2x + 6
.You do not need to check in your algorithm if the number is an integer or within the range. We will assume it is always entered correctly. However, you must attempt to code using the correct data type. Please check data types in the book for using positive integers that will be within the dened range
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned x=0, y=0;
printf("Enter a positive number between 0 to 300000000\n");
scanf("%u",&x);
y=(3*x*x)-(2*x)+6;
printf("\n\nThe value of y is %u",y);
return 0;
}
Upvotes: 0
Views: 281
Reputation: 15
because of value is bigger than the maxi. limit of integer data type so, if you enter value more than the range of integer than it will be roll over ,that's why you didn't got right value. so for this if you want to avoid this problem than you have to use long long integer than you will get right value
Upvotes: 0
Reputation: 2367
x cannot take the value -10. As stated in your question, you do not need to check for the value, because it is assumed to always be entered correctly. By using -10, you defeat the assumption. Just use only positive numbers in your checks.
EDIT: In addition, by using unsigned
you imply unsigned int
. The maximum number can only fit to an int, if the c-int you use is a 32-bit int, not a 16-bit int.
EDIT2: In addition to you having to use %u in the scanf function, you also need to output using the format given to you. That is you need to visualize your calculation line on screen.
The information given should already be enough for you to figure out the answer. This is an assignment, and you are supposed to do something on your own, right?
Upvotes: 0
Reputation: 31394
You are using the wrong format code for scanf
/printf
. %d
is a signed integer. Use %u
for unsigned integers.
What is happening is that scanf
with a %d
is reading the user input as a signed integer and will scan in a negative number. scanf
does not check the datatype of the variable you pass in so it does get stored in an unsigned variable - however it isn't stored as -10, since the variable is unsigned. Instead it will be a very large positive number becuase of how negative numbers are stored (Two's complement).
Correct input valiation takes some work, which is why your instructions say to ignore it.
Upvotes: 1