使用char和num扫描输入行

时间:2015-03-19 12:44:16

标签: c pointers

因此,我需要使用指针计算平均值而不使用字符串。用户将输入一个字母,然后输入一个空格,后跟一个数字(一个整数),该字母表示该数字是正数(p)还是负数(n),或者用户是否输入了数字(e)。 / p>

我知道我需要一个循环来连续读取数字并在总和中加上或减去它们直到字母" e"输入。

 program should have and use the following function
//    Precondition: value will be a pointer to where the input value is to     be stored. 
//    Postcondition: returns true if a number was read, or false if 
//    it was the end of the list. The int pointed to by value will be
//    set to the number input by this function, made negative or
//    positive depending on the character before it. int read_number(int*     value);

样品输入为p 20 p 20 p 10 p 10 e

输出:15

我现在的问题是我的循环只读取两个输入周期,即使这样它也不打印平均值。我也应该使用一个指针,但是根据我仍然不确定上下文的方向,我没有看到指针的用处。

#include <stdio.h>

//precondition: value will be a pointer to where the input value is to be stored.
int main(){

    int sum;
    int num;
    int counter;
    float avg;
    char let;
 scanf("%c %d", &let, &num);
    for (counter=0;let == 'n' || let == 'p'; counter++){
        scanf("%c %d", &let, &num);
                if ( let == 'n'){
                sum-=num;
                }
                if (let == 'p'){
                sum+=num;
                }
        if ( let == 'e'){
             avg=sum/counter;
            printf("%f", &avg);
        }

            }
    return 0;

}

1 个答案:

答案 0 :(得分:1)

您的输入是:p 20 p 20 p 10 p 10 e 循环前scanf扫描'p',然后跳过该空格,然后扫描20。循环中的下一个scanf读取空格,因为它也是一个字符,而%d无法扫描int并停止扫描。看到问题了?

要解决此问题,请更改

scanf("%c %d", &let, &num);

scanf(" %c %d", &let, &num);//Note the space before %c

%c之前的空格吞噬空格字符(如果有的话),如换行符,空格等,直到第一个非空白字符。

其他问题包括未将sum初始化为0并在&avg下方使用avg代替printf

printf("%f", &avg);