C中的计算器程序问题

时间:2012-10-06 21:55:03

标签: c function calculator

我正在编写一个统计计算器,有3种不同的计算选项。问题是每当我选择第二个选项时,它想要打印第一个选项和第二个选项的答案。当我选择3选项时,它只打印第3个选项的答案(错误的答案,但这可能是公式中的一个不幸事件)。结果如下:

Please Enter a number of inputs
3
Please enter number 1
1
Please enter number 2
2
Please enter number 3
3
Statistical Calculator Menu
(1) Mean
(2) Standard Deviation
(3) Range
(4) Restart/Exit
2
Here is the Mean 2.0Standard Devition is 0.8

现在我认为这可能是我如何调用每个函数的问题,但我能说的最好不是这样。然后我认为它可能是一个我没有初始化的值,但似乎不是它。我只需要另一双眼睛看看我在哪里出错了。

#include <stdio.h>
#include <conio.h>
#include <math.h>

const int MAX_DATA=8;
void menu(float numbers[], int amount);
float mean(float numbers[],int amount);
float standard_dev(float numbers[], int amount);
float range( float numbers[], int amount);

int main()
{
    int i=0, amount=0;
    float numbers[MAX_DATA];
    printf("Please Enter a number of inputs \n");
    scanf("%d", &amount);
    if (amount>MAX_DATA)
    {
        printf("You entered too many numbers");
    }
    else
    {
        for (i=0; i<amount; i++)
        {
            printf("Please enter number %d\n", i+1);
            scanf("%f",&numbers[i]);
        }
        menu(numbers,amount);
    }
    getch();
    return 0;
}
void menu(float numbers[],int amount)
{
    int input2=0;
    printf("Statistical Calculator Menu");
    printf("\n(1) Mean\n(2) Standard Deviation\n(3) Range\n(4) Restart/Exit\n");
    scanf("%d",&input2);
    if(input2==1)
    {
        mean(numbers,amount);
    }
    if  (input2==2)
    {
        standard_dev(numbers,amount);
    }
    if (input2==3)
    {
        range(numbers,amount);
    }
}
float mean(float numbers[],int amount)
{
    int i;
    float sum=0;
    float average=0;
    for (i=0; i<amount; i++)
    {
        sum=sum+numbers[i];
    }
    average=sum/amount;
    printf("Here is the Mean %.1f", average);
    return average;
}
float standard_dev(float numbers[], int amount)
{
    float sdev=0,dev=0,sumsqr=0,variance=0;
    int i;
    float mean2=0;
    mean2=mean(numbers,amount);
    for (i=0; i<amount; i++)
    {
        dev=numbers[i]-mean2;
        sumsqr+=dev*dev;
    }
    variance=sumsqr/(float)amount;
    sdev=sqrt(variance);
    printf("Standard Devition is %.1f", sdev);
    return sdev;
}
float range(float numbers[],int amount)
{
    int i;
    float diff=0;
    for (i=0; i<=amount; i++)
    {
        diff=numbers[amount]-numbers[1];
    }
    printf("%f\n",diff);
    return diff;
}

1 个答案:

答案 0 :(得分:1)

float standard_dev(float numbers[], int amount)
{
 float sdev=0,dev=0,sumsqr=0,variance=0;
 int i;
 float mean2=0;
 mean2=mean(numbers,amount); // Here it is.

它调用mean函数,它实际上打印了一些东西:)你可以在函数中添加布尔标志shouldPrint,并在打印时将其传递给true

此外,通过简单调试代码,这个问题很容易解决......如果实际看起来似乎没有帮助......