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

来源:互联网 发布:java 日志输出 编辑:程序博客网 时间:2024/04/30 09:37

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

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

代码块

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

#include <stdio.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));    return 0;}

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

#include <stdio.h>#include <math.h>void input();                                //定义输入函数void value();                                //定义平方根输出函数int n;                                       //定义全局变量int main(){    input();                                 //调用输入函数    value();                                 //调用平方根输出函数    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);}
阅读全文
0 0