Reputation: 49
I have this simple code in C, whenever I enter an id number that longer than 9 digits, it prints a different number. What's the wrong?
void main() {
long id1;
double l1, w1;
printf("enter studint 1 id,lenght and weight: \n");
scanf("%ld %lf %lf", &id1, &l1, &w1);
printf("STUDINTS INFORMATION:");
printf("\n\n%-10.0ld\t %-4.3lf\t %-4.3lf\n", id1, l1, w1);
}
Upvotes: 1
Views: 544
Reputation: 144770
You use type long
for id1
which may have range of just -2147483647
to 2147483647
depending on the target system architecture. This type cannot be used to store larger numbers on your system.
Incidentally, the format %-10.0ld
for id1
seems incorrect as the output for the value 0
will be just 10 spaces. The precision field does not specify the number of decimals for integers, but the minimum number of digits.
Note also that main
without arguments should have a prototype of int main(void)
, and you should test the return value of scanf()
to avoid undefined behavior on invalid input.
To solve your problem, here are possible solutions:
You could use type double
but I would not advise so.
You could try type long long int
, but this type may not be fully supported on your system.
I suggest you use a character string for your purpose.
Here is a modified version:
#include <stdio.h>
int main(void) {
char id1[20];
double l1, w1;
printf("enter student 1 id, height and weight:\n");
if (scanf("%19s%lf%lf", id1, &l1, &w1) != 3) {
printf("invalid input\n");
return 1;
}
printf("STUDENT INFORMATION:\n");
printf("\n%-10s\t %-4.3f\t %-4.3f\n", id1, l1, w1);
return 0;
}
Upvotes: 1
Reputation: 3987
That's because range of long in C is from -2,147,483,648 to 2,147,483,647. So, when you try to save a number longer than 9 digits it gets out of range.
For more details on the range of variables in C: https://www.tutorialspoint.com/cprogramming/c_data_types.htm
Upvotes: 0
Reputation: 249153
Usually, IDs are better stored as strings. Not only is it more flexible if the ID someday contains letters, but it avoids problems like this. IDs are not arithmetic, i.e. you cannot typically get anything out of adding or subtracting them, so you may as well just store them as strings. Then you can easily support any length, regardless of the width of various integer types on your system.
Upvotes: 0