1
0

checking.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // checking.c -- validating input
  2. #include <stdio.h>
  3. #include <stdbool.h>
  4. // validate that input is an integer
  5. long get_long(void);
  6. // validate that range limits are valid
  7. bool bad_limits(long begin, long end,
  8. long low, long high);
  9. // calculate the sum of the squares of the integers
  10. // a through b
  11. double sum_squares(long a, long b);
  12. int main(void)
  13. {
  14. const long MIN = -10000000L; // lower limit to range
  15. const long MAX = +10000000L; // upper limit to range
  16. long start; // start of range
  17. long stop; // end of range
  18. double answer;
  19. printf("This program computes the sum of the squares of "
  20. "integers in a range.\nThe lower bound should not "
  21. "be less than -10000000 and\nthe upper bound "
  22. "should not be more than +10000000.\nEnter the "
  23. "limits (enter 0 for both limits to quit):\n"
  24. "lower limit: ");
  25. start = get_long();
  26. printf("upper limit: ");
  27. stop = get_long();
  28. while (start !=0 || stop != 0)
  29. {
  30. if (bad_limits(start, stop, MIN, MAX))
  31. printf("Please try again.\n");
  32. else
  33. {
  34. answer = sum_squares(start, stop);
  35. printf("The sum of the squares of the integers ");
  36. printf("from %ld to %ld is %g\n",
  37. start, stop, answer);
  38. }
  39. printf("Enter the limits (enter 0 for both "
  40. "limits to quit):\n");
  41. printf("lower limit: ");
  42. start = get_long();
  43. printf("upper limit: ");
  44. stop = get_long();
  45. }
  46. printf("Done.\n");
  47. return 0;
  48. }
  49. long get_long(void)
  50. {
  51. long input;
  52. char ch;
  53. while (scanf("%ld", &input) != 1)
  54. {
  55. while ((ch = getchar()) != '\n')
  56. putchar(ch); // dispose of bad input
  57. printf(" is not an integer.\nPlease enter an ");
  58. printf("integer value, such as 25, -178, or 3: ");
  59. }
  60. return input;
  61. }
  62. double sum_squares(long a, long b)
  63. {
  64. double total = 0;
  65. long i;
  66. for (i = a; i <= b; i++)
  67. total += (double)i * (double)i;
  68. return total;
  69. }
  70. bool bad_limits(long begin, long end,
  71. long low, long high)
  72. {
  73. bool not_good = false;
  74. if (begin > end)
  75. {
  76. printf("%ld isn't smaller than %ld.\n", begin, end);
  77. not_good = true;
  78. }
  79. if (begin < low || end < low)
  80. {
  81. printf("Values must be %ld or greater.\n", low);
  82. not_good = true;
  83. }
  84. if (begin > high || end > high)
  85. {
  86. printf("Values must be %ld or less.\n", high);
  87. not_good = true;
  88. }
  89. return not_good;
  90. }