C#英里每加仑计算器输出始终为1,求代码结构兼容的修复方案
It sounds like you’re hitting a common snag with your C# MPG calculator—let’s break down the most likely causes and fix them while keeping your existing code structure intact.
First, let’s recap the correct formula for MPG:MPG = Miles Driven / Gallons of Fuel Used
Here are the top issues that would cause your output to always be 1, along with corrected code snippets matching your initial structure:
1. Accidentally Hardcoding MPG to 1
The simplest culprit is if you’ve mistakenly set MPG = 1; instead of calculating it using the input values. Replace that line with the proper division:
namespace Miles_Per_Gallon { class Program { static void Main(string[] args) { float Miles, Gallons, MPG; string textline; // Get miles input Console.Write("Enter miles driven: "); textline = Console.ReadLine(); Miles = float.Parse(textline); // Get gallons input Console.Write("Enter gallons used: "); textline = Console.ReadLine(); Gallons = float.Parse(textline); // Calculate MPG (this is the critical fix!) MPG = Miles / Gallons; // Not MPG = 1; // Output the result Console.WriteLine($"Miles per gallon: {MPG:F2}"); } } }
2. Integer Division Accidents
Even if you declared Miles and Gallons as float, if you’re parsing input as integers first (e.g., int.Parse()), you might be doing integer division before assigning to the float variable. For example:
// Wrong: Integer division truncates results before storing in float Miles = int.Parse(textline); Gallons = int.Parse(textline); MPG = Miles / Gallons; // Only returns 1 if Miles and Gallons are equal integers
Fix: Use float.Parse() or Convert.ToSingle() to keep the values as floats from the start, as shown in the first snippet.
3. Swapped Variables (Unlikely but Worth Checking)
If you wrote MPG = Gallons / Miles; instead of Miles / Gallons, you’d only get 1 if Miles equals Gallons—but if this happens every time, you probably have a hardcoded value instead. Double-check the order in your division line.
Once you fix the calculation line to use the proper division of Miles by Gallons, your calculator should start returning accurate values instead of always 1.
内容的提问来源于stack exchange,提问作者Cole Udall

