C语言scanf函数逐字符读取输入示例

最近在看《C语言程序设计:现代方法》,scanf函数可以逐字符读取用户输入,也就是可以一边接收输入一边处理,这倒是个好主意,下边两个例子,一个是书中的例子,一个是练习题。

读取输入然后求和,要求是当用户输入0的时候程序给出求和结果,代码如下

#include <stdio.h>

int

main(void)

{

    int n,sum = 0;

    printf("THis program sums a series of number.\n");

    printf("Enter number (0 to terminate): ");

    scanf("%d",&n);

    while (n != 0){

        sum += n;

        scanf("%d",&n);

    }

    printf("The sum is: %d.\n",sum);

    return 0;

}

下边的是练习题,要求是不断提示用户输入数字,可小数,可负数,输入为0时停止,然户求输入的数中最大的一个

#include <stdio.h>

int

main(void)

{

    float fn,max = 0;

    printf("Enter a number: ");

    scanf("%f",&fn);

    while (fn != 0){

        max = max >= fn ? max : fn;

        printf("Enter a number: ");

        scanf("%f",&fn);

    }

    printf("%.2f\n",max);

    return 0;

}


posted on 2011-10-14 23:11  DeadLoop  阅读(1853)  评论(0编辑  收藏  举报