平均值生成负十进制数

时间:2015-07-12 16:14:52

标签: c function average

我创建了一个名为average的函数来计算平均年龄。它是如何产生一个奇怪的负小数点。它工作正常,直到我把strcmp函数给进入德克萨斯州的人。示例年龄:20 50 20 30& 40生成平均年龄为-243454739.00。 有人能指出我正确的方向,谢谢。

#include <stdio.h>
#include <string.h>

int main()
{
    //function decleration
    float average ( int A, int n);

    //int deleceration
    char names, states, statedata[100], namedata[100];
    int agedata[100], age, count = 0, A, n, avg;
    float a;

    //Get User Input 
    printf("Enter Number of family members being enter into program \n");
    scanf("%d", &n);

    //Name Loop
    for (names=0; names<n; ++names)
    {
        printf("Enter Family members name:\n");
        scanf("%s", &namedata);

        //Age Loop
        for (age=0; age<1; ++age)
        {       
            printf("Enter family members age:\n");
            scanf("%d", &agedata[age]);
            A +=agedata[age];
            count= count + 1;

            //State Loop
            for (states=0; states<1; ++states)
            {
                printf("Enter Family members state:\n");
                scanf("%s", &statedata);

                //strcmp function for state name "Texas" Selection
                if (strcmp(statedata,"texas")==0)
                {
                    printf("Family members who live in texas\n");
                    printf("%s\n", namedata);   
                }           
            }               
        }
    }

    // Average function call
    a = average(A, n);
    printf("The average age is %.2f\n", a);

    return 0;   
}   

//A declarator
float average( int A, int  n){
   float average;
   average = A / n;
   return average;
}   

1 个答案:

答案 0 :(得分:3)

A中将0初始化为main()。未初始化的局部变量在C中具有 indeterminate 值。

其他问题:

1)

scanf("%s", &namedata);
scanf("%s", &statedata);

Shoud be

scanf("%s", namedata);
scanf("%s", statedata);

由于scanf()在格式说明符char*时需要%s,而您正在传递char(*)[100]

2)

年龄的所有值均使用int类型。因此,让函数average()返回float仍然会产生int结果。 将类型A(在main()中)和函数参数A(在average()中)更改为float

3)

您的内心正在运行0..1,即只运行一次。所以你真的不需要那些循环。