请求协助编写Yards转Miles、Furlongs及Yards的转换函数
Fixing Your Yards to Miles/Furlongs/Yards Conversion Function
Hey there! Let's get that conversion function working properly. First, let's recap the rules to make sure we're on the same page:
- 1 Mile = 8 Furlongs = 1760 Yards
- 1 Furlong = 220 Yards
Looking at your current code, I see two key gaps:
- You're not using
Math.floor()for furlongs, which means you might end up with decimal values instead of whole, valid furlong counts - You haven't accounted for the final remaining yards after calculating miles and furlongs, and you're not building the readable string output
Here's a complete, working version of the function with step-by-step breakdowns:
function milesFurlongsYards(yards) { // Define clear conversion constants to avoid confusing "magic numbers" const MILE_TO_YARD = 1760; const FURLONG_TO_YARD = 220; // Calculate full miles and leftover yards after accounting for miles const miles = Math.floor(yards / MILE_TO_YARD); const yardsAfterMiles = yards % MILE_TO_YARD; // Calculate full furlongs from the leftover yards, then get the final remaining yards const furlongs = Math.floor(yardsAfterMiles / FURLONG_TO_YARD); const remainingYards = yardsAfterMiles % FURLONG_TO_YARD; // Build the result array — only include parts that have a non-zero value const resultParts = []; if (miles > 0) resultParts.push(`${miles}m`); if (furlongs > 0) resultParts.push(`${furlongs}f`); if (remainingYards > 0) resultParts.push(`${remainingYards}y`); // Join the parts with spaces for a clean, readable output return resultParts.join(' '); } // Test your example cases console.log(milesFurlongsYards(1760)); // Output: '1m' console.log(milesFurlongsYards(2220)); // Output: '1m 2f' console.log(milesFurlongsYards(2224)); // Output: '1m 2f 4y'
Let's walk through the logic:
- Constants: Named conversion values make the code easier to read and update later if needed.
- Miles Calculation:
Math.floor(yards / 1760)gives us the number of complete miles, whileyards % 1760keeps the yards that don't add up to a full mile. - Furlongs & Remaining Yards: We repeat the same division/remainder logic on the leftover yards to get valid furlongs, then the final remainder is the yards that don't make up a full furlong.
- Result Assembly: We only include parts with positive values (so we never get outputs like
0m 0f 5y), then join them with spaces for the clean format you need.
This should handle all your test cases perfectly!
内容的提问来源于stack exchange,提问作者James Johnson
相关产品推荐
相关产品推荐

