#include stdio.h#include stdbool.hlong get_long(void);bool isWrongInput(long begin, long end,long low, long high);
编程学习网为您整理以下代码实例,主要实现:使用函数验证输入,希望可以帮到各位朋友。
#include <stdio.h>
#include <stdbool.h>
long get_long(voID);
bool isWronginput(long begin, long end,long low, long high);
double sum_squares(long a, long b);
int main(voID)
{
const long MIN = -10000000L; // lower limit to range
const long MAX = +10000000L; // upper limit to range
long start; // start of range
long stop; // end of range
double answer;
//from w w w . j av a 2 s .c om
printf("Enter the limits (0 to quit)lower limit\n: ");
start = get_long();
printf("upper limit: ");
stop = get_long();
while (start !=0 || stop != 0)
{
if (isWronginput(start, stop, MIN, MAX))
printf("Please try again.\n");
else
{
answer = sum_squares(start, stop);
printf("The sum of the squares of the integers ");
printf("from %ld to %ld is %g\n", start, stop, answer);
}
printf("Enter the limits (enter 0 for both " "limits to quit):\n");
printf("lower limit: ");
start = get_long();
printf("upper limit: ");
stop = get_long();
}
printf("Done.\n");
return 0;
}
long get_long(voID)
{
long input;
char ch;
while (scanf("%ld", &input) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch); // dispose of bad input
printf(" is not an integer.\n");
}
return input;
}
double sum_squares(long a, long b)
{
double total = 0;
long i;
for (i = a; i <= b; i++)
total += (double)i * (double)i;
return total;
}
bool isWronginput(long begin, long end,
long low, long high)
{
bool not_good = false;
if (begin > end)
{
printf("%ld isn't smaller than %ld.\n", begin, end);
not_good = true;
}
if (begin < low || end < low)
{
printf("Values must be %ld or greater.\n", low);
not_good = true;
}
if (begin > high || end > high)
{
printf("Values must be %ld or less.\n", high);
not_good = true;
}
return not_good;
}
沃梦达教程
本文标题为:使用函数验证输入
基础教程推荐
猜你喜欢
- C++定义类对象 1970-01-01
- C++按值调用 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- C++ #define 1970-01-01
- 初始化变量和赋值运算符 1970-01-01
- C语言访问数组元素 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- C++输入/输出运算符重载 1970-01-01