C#中的简单数学问题

Fre*_*red 5 c# math command-line percentage

我有这个程序,每个可能200分中取3分,然后应该得到平均值并显示百分比.但是当我输入数字时,我得到00.0作为答案.我能做错什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int Score1;
            int Score2;
            int Score3;

            Console.Write("Enter your score (out of 200 possible) on the first test: ");

            Score1 = int.Parse(Console.ReadLine());
            Console.Write("Enter your score (out of 200 possible) on the second test: ");

            Score2 = int.Parse(Console.ReadLine());
            Console.Write("Enter your score (out of 200 possible on the third test: ");

            Score3 = int.Parse(Console.ReadLine());
            Console.WriteLine("\n");

            float percent = (( Score1+ Score2+ Score3) / 600);

            Console.WriteLine("Your percentage to date is: {0:00.0}", percent);
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 17

您将整数除以整数 - 即使您将结果分配给a,也总是使用整数运算float.最简单的修复方法是使其中一个操作数浮动,例如

float percent = (Score1 + Score2 + Score3) / 600f;
Run Code Online (Sandbox Code Playgroud)

请注意,这实际上不会给你一个百分比 - 它会给你一个介于0和1之间的数字(假设输入介于0和200之间).

要获得实际百分比,您需要乘以100 - 这相当于仅除以6:

float percent = (Score1 + Score2 + Score3) / 6f;
Run Code Online (Sandbox Code Playgroud)

  • 活泉?你怎么能在不到33秒的时间里输入它?:-P (4认同)
  • @Patrick:这里的第一行:http://meta.stackexchange.com/questions/9134/jon-skeet-facts/9135#9135;) (2认同)