如何让这个 C 程序工作,它不断打印"Insert value"两次?



我正在努力让这个c程序工作,它在每次输出后都会打印两次"插入值",我的平均值也不起作用。

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
void main()
{
    int d = 0;
    printf("Command list:t nnCommand: t Output: ");
    printf("n "A"  t Declare values of a list.n "O"  t Obtain the average value of the values in the list.n");
    printf(" "P"  t Print the values of the list.n "S"  t End program. n");
    while (d !=1)
    {
        char value;
        printf("nInsert value: ");
        scanf("%c", &value);

        if (value == 'S' || value == 's')
        {
            d++;
        }

        float list[1000], average, sum = 0;
        int number_of_values;
    //in order to insert values to array:
        if (value == 'a' || value == 'A')
        {
            printf("Insert number of values in the list: ");
            scanf("%d", &number_of_values);
            for (int i = 1; i<=number_of_values; i++)
            {
                printf("Insert Value of element %d on the list: ", i);
                scanf("%f", &list[i]);
                sum += list[i];
            }
        }
        if ((value == 'P' || value == 'p') && (number_of_values >= 1))
        {
            for (int i =1; i<= number_of_values; i++)
            {
                printf("%.2fn", list[i]);
            }
        }
        if ((value == 'o' || value == 'O') && (number_of_values >= 1))
        {
            average = sum / number_of_values;
            printf("Average = %.2f", average);
        }

    }
}

while循环中,在此-中的%c之前留一个空格

scanf(" %c", &value);

您的scanf会返回,因为当您按enter键进行输入后,stdin中会出现'n'scanf读取直到遇到'n'

当你使用scanf在数组中输入并按下enter键时,'n'留在缓冲区中,当循环迭代并再次在value中输入时,它会遇到'n'scanf返回而不输入。这就是为什么你需要在%c之前添加空格。

并将这些声明从while循环中移出-

float list[1000], average, sum = 0;
int number_of_values;
while(b!=1){
//your code
}

如果在循环中声明变量,则由于再次声明,它们在每次迭代后都会重置。

注意-void main()->int main(void)int main(int argc,char **argv)

您的代码读取字符,因此第一条"插入值"消息是在任何其他scanf()之后按"enter"引起的。您可以获得整数1,2,3等命令。

另一种可能的解决方案是,您可以插入"getch()";while循环结束时的代码,以便获得存储在缓冲区中的"回车"字符。

最新更新