We have introduced a number of basic data types in class: floats/doubles, ints/shorts/longs, chars, etc.
Understanding some of their limitations, and being able to examine them through code, is an important part of being able to use them effectively.
Real numbers are represented through floats and doubles (plus unsigned variants), each of which has a limit on both the magnitude and precision of the numbers it can represent. Internally we can consider the numbers stored like 1.23456 x 10whatever. The precision dictates how many decimal places are supported in the 1.23456... and the magnitude dictates how large "whatever" can be.
Integers are represented through shorts, ints, and longs (plus unsigned variants), each of which can represent values within a specific range of integers (e.g. -2N-1 ... 2N-1-1)
#include <cstdio> #include <cfloat> int main() { printf( "Largest float value %f\n", FLT_MAX); printf( "Largest double value %lf\n", DBL_MAX); printf( "Smallest float value %f\n", FLT_MIN); printf( "Smallest double value %lf\n", DBL_MIN); printf( "Maximum precision (sig. digits) of a float %d\n", FLT_DIG); printf( "Maximum precision (sig. digits) of a double %d\n", DBL_DIG); } |
#include <cstdio> #include <climits> int main() { cout << "Largest short: %d\n", SHRT_MAX); cout << "Largest int: %d\n", INT_MAX); cout << "Largest long: %ld\n", LONG_MAX); cout << "Smallest short: %d\n", SHRT_MIN); cout << "Smallest int: %d\n", INT_MIN); cout << "Smallest long: %ld\n", LONG_MIN); } |
#include &cstdio> int main() { // is -1 true or false? if (-1) printf( "-1 is true\n"); else printf( "-1 is false\n"); // is 0 true or false? if (0) printf( "0 is true\n"); else printf( "0 is false\n"); // is 1 true or false? if (1) printf( "1 is true\n"); else printf( "1 is false\n"); // is 57 true or false? if (57) printf( "57 is true\n"); else printf( "57 is false\n"); return 0; } |
#include <cstdio> int main() { int val; do { printf( "Enter an ascii value (1-127) to examine or 0 to quit:"); scanf("%d", &val); if ((val > 0) && (val < 128)) { printf( "\'\\" %d \' = \' %c \'\n", val, ((char)(val)); } else if (val != 0) printf( "Must be in range 1-127\n"); } while (val != 0); return 0; } |