首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

老师布置的选做题解决思路

2012-06-04 
老师布置的选做题给定一个整数,并由键盘输入若干个数,找出与预先给定的数最近的数,并指出它是由键盘输入的

老师布置的选做题
给定一个整数,并由键盘输入若干个数,找出与预先给定的数最近的数,并指出它是由键盘输入的第几个数。 

指针没学到,刚学了数组,如何处理?

[解决办法]
随手写了一个代码,但是不完善,如果第一次输入负数就是错误的

C/C++ code
#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/* 

热点排行