zl程序教程

您现在的位置是:首页 >  其他

当前栏目

习题 4.5 从键盘上输入一个小于1000的正数,要求输出它的平方根(如平方根不是整数,则输出其整数部分)。要求在输入数据后先对其进行检查是否为小于1000的正数。若不是,则要求重新输入。

输入输出数据 一个 进行 是否 部分 检查
2023-09-14 09:06:56 时间

C程序设计 (第四版) 谭浩强 习题4.5 个人设计

习题 4.5 从键盘上输入一个小于1000的正数,要求输出它的平方根(如平方根不是整数,则输出其整数部分)。要求在输入数据后先对其进行检查是否为小于1000的正数。若不是,则要求重新输入。

代码块

方法1:(利用循环结构)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    int x;
    float y;
    printf("Please enter number:");
    scanf("%d", &x);
    while (x >= 1000){
        printf("Please enter number:");
        scanf("%d", &x);
    }
    y = sqrt(x);
    printf("%d value is %d\n", x, int(y));
    system("pause");
    return 0;
}

方法2:(利用函数的模块化设计)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void input();                                //定义输入函数
void value();                                //定义平方根输出函数
int n;                                       //定义全局变量
int main()
{
	input();                                 //调用输入函数
	value();                                 //调用平方根输出函数
	system("pause");
	return 0;
}
//输入函数
void input()
{
	printf("Please enter number:");
	scanf("%d", &n);
}
//平方根输出函数
void value()
{
	double y;
	while (n >= 1000)
		input();                             //此处调用输入函数
    y = sqrt(n);
    printf("%d value is %d\n", n, (int)y);
}

方法3:(动态分配内存)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void input(int *n);
void sqr(int n);
int main()
{
	int *num=(int*)malloc(sizeof(int));
	input(num);
	sqr(*num);
	system("pause");
	return 0;
}
void input(int *n)
{
	printf("Enter number: ");
	scanf("%d", n);
	while(*n>=1000||*n<0){
		printf("Error! Enter number: ");
		scanf("%d", n);
	}
}
void sqr(int n)
{
	double r=sqrt((double)n);
	printf("Result: %.lf\n", r);
}