5

私は、可能な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();
        }
    }
}
4

4 に答える 4

17

整数を整数で割っています。これは、結果を に代入している場合でも、常に整数演算を使用しますfloat。これを修正する最も簡単な方法は、オペランドの 1 つを float にすることです。

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

ただし、これは実際にはパーセンテージを提供しないことに注意してください-0から1の間の数値が得られます(入力が0から200の間であると仮定)。

実際のパーセンテージを取得するには、100 を掛ける必要があります。これは、6 で割るだけに相当します。

float percent = (Score1 + Score2 + Score3) / 6f;
于 2010-09-13T08:25:23.513 に答える
3

パーセンテージを計算していません。ユーザーが最大スコアを入力すると想像してください: 200 + 200 + 200 = 600、これを 600 = 1 で割ります。いずれかのスコアが 200 未満で入力されると、合計は 1 未満になり、0 に切り捨てられます。それらをfloatとして保存し(丸めによって情報が失われないようにするため)、100を掛けます。

于 2010-09-13T08:31:20.417 に答える
2

それはデータ型の問題だと思います。変数パーセントは float であり、すべてのスコアは int であるため、スコアの 1 つを float に型キャストする必要があります。

于 2010-09-13T08:37:20.973 に答える
0
using System;

namespace stackOverflow
{
    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");
            var percent = ((Score1 + Score2 + Score3) / 6D);
            Console.WriteLine("Your percentage to date is: {0:00.0}", percent);
            Console.ReadLine();

        }
    } 

}
于 2010-09-13T09:52:57.533 に答える