• 这是我写的半成品程序,我输入一个字母而不是整数等时候,会陷入死循环,原因尚未明确,暂记录于此


     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #define MAX     5
     4 int input(int *array, int n)
     5 {
     6         int i;
     7         printf("请输入 %d 个数
    ", n);
     8         for (i = 0; i < n; i++) {
     9                 printf("第 %d 个数 :", i + 1);
    10                 scanf("%d", &array[i]);
    11                 while (i > 0 && i < MAX && (array[i] < array[i - 1])) {
    12                         printf("less than previus number, try again!
    ");
    13                         scanf("%d", &array[i]);
    14                 }
    15                 if (i == MAX - 1)
    16                         printf("already completed input!
    ");
    17         }
    18 }
    19 
    20 int search(int *array, int n, int key)
    21 {
    22         while (array[n - 1] != key)
    23                 n--;
    24         return n;
    25 }
    26 
    27 int main()
    28 {
    29         int n;
    30         int array[MAX];
    31         input(array, MAX);
    32         while (1) {
    33                 int key;
    34                 printf("输入欲查找的数,并回车:
    ");
    35                 scanf("%d", &key);
    36                 n = search(array, MAX, key);
    37                 printf("the number you entered locates in %d  
     ", n);
    38         }
    39         return 0;
    40 }

     经查,《C程序设计语言》(第二版.新版)138页,是这样说的“当scanf函数扫描完其格式串,或者碰到某些输入无法与格式控制说明匹配的情况时,该函数将中止”,

    “该函数将中止”,所以就进入了while(1)的循环中。

  • 相关阅读:
    表单工具可以什么
    页面嵌套的方式展现报表
    EChars图类型
    SVG图类型
    JSP <c:import>和<jsp:include>区别【转】
    Servlet配置
    jsp的scope属性【转载】
    Cookie、Session【转载】
    page、request、session、application区别【转载】
    C++笔记------static 和 const 在类中用法
  • 原文地址:https://www.cnblogs.com/hare/p/3463314.html
Copyright © 2020-2023  润新知