代码块
方法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); }