c - 使用 char 和 num 扫描输入行

标签 c pointers

所以我正在解决这个问题,我需要使用指针而不使用字符串来计算平均值。用户将输入一个字母,然后输入一个空格,后跟一个数字(整数),该字母指示该数字是正数(p)还是负数(n),或者用户是否已完成输入数字(e)。

我知道我需要一个循环来不断读取数字并从总和中添加或减去它们,直到输入字母“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;

}

最佳答案

您的输入是: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 以及在下面的 printf 中使用 &avg 而不是 avg

printf("%f", &avg);

关于c - 使用 char 和 num 扫描输入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29144944/

相关文章:

c - 如何将一个没有元素的数组复制到输出文件,使其包含一个空数组?

带模板的 C++ 函数指针

c - Scanf 未按预期运行

c 扫描二维数组

c - 在 C 中提取 double 的最右边 N 位

c++ - 使用奇数流中的模生成 'random' 数字

c++ - 在 C 中读取 JPEG 文件的 RGB 三元组

c - C中sizeof计算char a[]和char *a有什么区别?

c - 从 C 函数中创建的数组返回数组元素?

c++ - C 和 C++ 函数指针兼容吗?