You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 圆弧直线路径坐标计算中如何将Y值转换为整数输出

C# 坐标输出Y值整数化修改方案

核心实现依赖C#内置的Math.Round()方法完成四舍五入逻辑,插入位置为Y值所有计算逻辑结束后、输出语句之前即可,以下是两种可选实现方案:

方案1:直接修改Y变量为四舍五入后的值

适合后续不需要用到原始浮点精度Y值的场景,修改后完整代码如下:

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

namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            double Xmin = -9, Xmax = 9, dX = 2, T = 2, Y;
            Console.WriteLine("|   X    |   Y    |");
            for ( double X = Xmin; X <= Xmax; X += dX )
            {
                Y = T;
                if (X >= -9 && X <= -6) Y = Math.Sqrt(Math.Pow(3, 2) - Math.Pow(X + 6, 2));
                if (X >= -6 && X <= -3) Y = X + 3;
                if (X >= -3 && X <=  0) Y = Math.Sqrt(Math.Pow(3, 2) - Math.Pow(X, 2));
                if (X >=  0 && X <=  3) Y = X - 3;
                if (X >=  3 && X <=  9) Y = 0.5 * X - 1.5;
                // 新增四舍五入逻辑
                Y = Math.Round(Y);
                Console.WriteLine("| {0,6} | {1,6} |", X, Y);
            }
           Console.ReadKey();
        } 
    }
}

方案2:输出时临时处理Y值

适合后续逻辑还需要保留原始浮点精度Y值的场景,仅修改输出语句即可:

// 仅替换原有Console.WriteLine行即可
Console.WriteLine("| {0,6} | {1,6} |", X, Math.Round(Y));

如果需要明确转为int类型避免后续运算出现精度问题,可以将四舍五入后的结果强制转换:

int intY = (int)Math.Round(Y);

注:原代码首行Using System首字母大写属于笔误,C#语法要求关键字小写,已在上述修改代码中修正。

内容的提问来源于stack exchange,提问作者Kamel Avad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:45:06