老师布置的选做题
给定一个整数,并由键盘输入若干个数,找出与预先给定的数最近的数,并指出它是由键盘输入的第几个数。
指针没学到,刚学了数组,如何处理?
[解决办法]
随手写了一个代码,但是不完善,如果第一次输入负数就是错误的
#include <stdlib.h>#include <stdio.h>#include <limits.h>int main(int argc, char **argv){ int spec_num = 10; int input; int the_num = INT_MAX + spec_num; // 初始化为最大的整数 + spec_num,会溢出,但是不影响 int i = 0, n; while (1) { scanf("%d", &input); i++; // 以负数作为结束标志 if (input < 0) break; // 比较距离 if (abs(input - spec_num) < abs(the_num - spec_num)) { // 记录最接近的值 the_num = input; n = i; } } printf("the %dth num is the nearest with spec num %d, it is %d\n", n, spec_num, the_num); return 0;}/*输入输出:12 13 4 18 9 45 -1the 5th num is the nearest with spec num 10, it is 9/*