C# C语言中的简单数学问题#
我有一个程序,从可能的200分中抽取3分,然后得到平均值并显示百分比。但当我输入数字时,我得到的答案是00.0。 我可能做错了什么C# C语言中的简单数学问题#,c#,math,command-line,percentage,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)
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();
}
}
}
您正在将一个整数除以一个整数-这始终使用整数算术,即使您将结果分配给
浮点
。最简单的修复方法是将其中一个操作数设为浮点,例如
float percent = (Score1 + Score2 + Score3) / 600f;
请注意,这实际上不会给你一个百分比,它会给你一个介于0和1之间的数字(假设输入在0和200之间)
要得到一个实际的百分比,需要乘以100,这相当于只除以6:
float percent = (Score1 + Score2 + Score3) / 6f;
你不是在计算一个百分比。假设用户输入最大分数:200+200+200=600,除以600=1。如果任何一个分数低于200,则总数将小于1,并四舍五入为0。
您应该将它们存储为浮点数(以确保不会因舍入而丢失任何信息),然后乘以100。我认为这是一个数据类型问题。你应该输入一个分数来浮动,因为你的变量百分比是浮动的,所有分数都是整数。Woot?你怎么能在不到33秒的时间里打出来-P@Patrick:此处的第一行:;)我想这是C派生语言表达式语法中最常见的陷阱之一……这无疑是一个意想不到的陷阱,也是一个典型的贝纳问题。最常见的-不确定。但我要说的是,它保证在前十名之内;)而且是大多数人很早就发现的。
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();
}
}
}