如何使用c#计算控制台应用程序的平均值

时间:2012-08-05 08:27:51

标签: c# average

这是开发代码它的一个基本应用程序我需要帮助代码来计算平均值应该相等并显示3.00

    // Define constrants and variables
    // Constrants
    int MAX_RESPONSE = 5;
    int MIN_RESPONSE = 1;
    int MAX_QUESTIONS = 50;
    string scale5 = "5 - STRONGLY AGREE";
    string scale4 = "4 - AGREE";
    string scale3 = "3 - NEITHER AGREE NOT DISAGREE";
    string scale2 = "2 - DISAGREE";
    string scale1 = "1 - STRONGLY DISAGREE";
    string scale0 = "0 - UNABLE TO ANSWER";
    string Question = "Question : C# is better than C++. Do you\n";

        // Variables
        int Response = 0;
        int ValidResponseCount = 5;
        int NonResponseCount = 2;
        int QuestionCount = 7;
        int MaximumResponse = MIN_RESPONSE;
        int MinimumResponse = MAX_RESPONSE;
        int TotalResponse = 1;
        var AverageResponse = 0;

        //calculate
        AverageResponse = TotalResponse / ValidResponseCount;


        // Output results
        Console.WriteLine("SURVEY RECORDING SYSTEM ");
        Console.WriteLine(Question + "\n" +
            "\t" + scale5 + "\n" +
            "\t" + scale4 + "\n" +
            "\t" + scale3 + "\n" +
            "\t" + scale2 + "\n" +
            "\t" + scale1 + "\n" +
            "\t" + scale0 + "\n\n");
        Console.WriteLine("response value");
        Console.WriteLine("RESULTS " +
            "\n Number of valid responses     : " + ValidResponseCount +
            "\n Number of non responses       : " + NonResponseCount +
            "\n Number of times question asked: " + QuestionCount +
            "\n Maximum response              : " + MaximumResponse +
            "\n Minimum response              : " + MinimumResponse +
            "\n Average response value        : " + AverageResponse);

1 个答案:

答案 0 :(得分:2)

double AverageResponse = (double)TotalResponse / (double)ValidResponseCount;

会这么做 - 因为你正在使用整数,/将返回一个整数,可能会向上/向下舍入结果,转换为double会将此结果更改为有效的