0
votes

I have a problem here asking me to display the minimum and maximum a variable can store including: Short, Integer, Long and Float. I’m supposed to initilize it with one less than the correct answer, then add 1 to it to prove the variable doesn’t give an error. Example.

short srtMaximum = 32766;
srtMaximum += 1;
System.out.print(”Max value for short is “ + srtMaximum);

I’m supposed to do this for C and Java. Java I did no problem. Short is -32768, 32767 Int is -2,147,483,648, 2,147,483,647 Long -9quintillionL, 9 quintillionL Float was something I can’t remember off the top of my head

But with C is where I’m confused.
Short seems to be the same. But Long can only hold the same value as an Int? The documentation says an int can sometimes only be -32768 - 32767?

And I have no idea how to do this project with floats. No matter what value I assign the float to test it, it prints something different in printf

1
Perhaps you are looking for c's long long? - GBlodgett
(java)how about Integer.MAX_VALUE...? - Dang Nguyen
In Java, the numeric types are of a fixed size everywhere. Hence there exists constants such as Integer.MAX_VALUE and Integer.MIN_VALUE. If memory serves, in C, only a minimum size for each type is specified hence there is no direct comparison. - dave
Generally in C, sizeof(char) <= sizeof(short), sizeof(short) <= sizeof(int), sizeof(int) <= sizeof(long), and sizeof(long) <= sizeof(long long). The C specification says that sizeof(char) will always be equal to 1, and that long long` is at least a 64-bit type. You can find out the limits for the current implementation/target by using <stdint.h> and <limits.h> - Some programmer dude
The limits in C are platform dependent. The limits in Java are specified by the language, not the platform. - Dawood ibn Kareem

1 Answers

1
votes

You can use limits.h to figure out what the largest integer values are on your system. You can use float.h to figure out what the largest floating-point values are.

Here's an example for limits.h:

#include <limits.h>
#include <stdio.h>

int main() {
    printf("INT_MAX: %d\n", INT_MAX);
    printf("UINT_MAX: %u\n", UINT_MAX);
    printf("LONG_MAX: %ld\n", LONG_MAX);
    printf("ULONG_MAX: %lu\n", ULONG_MAX);
}

I am unsure what your instructor means by 'one less than the maximum float.' One less than the maximum float is not representable.

No matter what value I assign the float to test it, it prints something different in printf

Floating point cannot represent all numbers precisely. Here's how to tell if you can represent it precisely:

  1. Convert it to a fraction
  2. Reduce the fraction
  3. Check if the denominator is a power of two.

Example: Can 0.1 be precisely represented?

  1. First, convert it to a fraction: 1/10
  2. Next, reduce: 1/10
  3. 10 is not a power of two. Therefore, 0.1 cannot be precisely represented.