计算数组元素的百分比

标签 c arrays printf scanf percentage

我必须读取 10 个整数,计算每个值的 90%,以倒序打印它们,最后打印我获得的各种值的中间值。

但它不起作用,它只打印零。另一件事是,在我输入 10 个值后,它仍然需要另一个输入才能开始打印。我是 C 的新手,所以我可能犯了一个愚蠢的错误......

#include <stdio.h>

int main ()
{
    int n = 10;           //number of numbers
    float array[10];

    for(int i = 0 ; i < n ; i++) {                 
        scanf("%d \n", &array[i] ) ;   //read the keyboard input and memorize it in the array
    }

    for( int i = 9; i > -1 ; i-- ) {
        array[i] = array[i]*90.0/100.0;        //calculate the 90% of every value 
        printf("%f \n", array[i]);         //prints the values in opposite order
    }

    float s = 0;                         
    for(int i = 0 ; i < 10 ; i++){
        s = s+array[i];                    //add up all the values
    }

    float m =s/n;                          //calculate the mid value
    printf("%f \n",m);                     //prints it
    system("PAUSE");

    return 0;
}

最佳答案

这可能是你的问题:

scanf("%d \n", &array[i] ) ;   //read the keyboard input and memorize it in the array

array 元素的类型是float,您被告知scanf 读取一个整数。那里有未定义的行为。试试这个:

scanf("%f \n", &array[i] ) ;   //read the keyboard input and memorize it in the array

关于计算数组元素的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21053871/

相关文章:

c - C 中的分段 11

java - 使用 "for loop"添加数组值时发生异常

创建字符串的 vector char 数组

c - printf NULL 不带引号或非NULL,带引号的sql语句

c - 具有 `fcn( char *, ...)` 的可变参数函数如何知道何时结束?

c++ - VSCode错误: "incorrect use of va_start"

c - C 中的迭代二叉搜索树插入

c - 如何迭代获取特定的结构元素并将它们存储到 C 中的二维数组中?

c - C 中数组和指针的基本行为

c# - 为什么选择列表而不是数组?