1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
// Training 4.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include "time.h"
//#include <stdbool.h>
//validate that input is integer
int get_int(void);
//validate that range limits are valid
bool bad_limits(int begin, int end, int low, int high);
// calculate the sum of the squares of the integers
// a through b
double sum_squares(int a, int b);
int main(void)
{
const int MIN = -1000; // lower limit to range
const int MAX = 1000; // upper limit to range
int start; // start of range
int stop; // end of range
double answer;
time_t startime, stoptime;
printf("This program computes the sum of the squares of "
"integers in a range. \nThe lower bound should not "
"be less than -1000 and\nthe upper bound should not "
"be more than 1000.\nEnter the limits (enter 0 for "
"both limits to quit.):\nLower Limit: ");
start = get_int();
printf("Upper Limit: ");
stop = get_int();
while (start !=0 || stop !=0)
{
if (bad_limits(start, stop, MIN, MAX))
printf("Please Try Again.\n");
else
{
startime=time(NULL);
answer = sum_squares(start, stop);
stoptime=time(NULL);
printf("\nTime Lapsed %f seconds.\n\n", difftime(stoptime, startime));
printf("The sum of the squares of the integers ");
printf("from %d to %d is %g\n", start, stop, answer);
}
printf("Enter the limits (enter 0 for both to exit):\n");
printf("Lower Limit: ");
start = get_int();
printf("Upper Limit: ");
stop = get_int();
}
printf("Done. \n");
return 0;
}
int get_int(void)
{
int input;
char ch;
while (scanf("%d" , &input) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch); // dispose of bad input
printf(" is not an integer. \nPlease enter an integer value");
}
return input;
}
double sum_squares(int a, int b)
{
double total = 0;
int i;
// for (i = a, i <= b, i++)
for(i = a; i <= b; i++ )
{
total += i * i;
printf("%d %0.1f\n", i, total);
}
return total;
}
bool bad_limits(int begin, int end, int low, int high)
{
bool not_good = false;
if (begin > end)
{
printf("%d is not smaller that %d. \n", begin, end);
not_good = true;
}
if (begin < low || end < low)
{
printf("Values must be %d or greater.\n", low);
not_good = true;
}
if (begin > high || end > high)
{
printf("Values must be %d or lower.\n",high);
not_good = true;
}
return not_good;
}
|