c# - 周长为 n 的三角形
问题描述
我想打印有多少个三角形的周长为n。(整数边)。实际上我使用的公式是here。 T(n): n=偶数 --> n^2/48 | n=奇数 --> (n+3)^2/48。 这是我的代码:
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
double m = 0;
if(n%2==0)
{
m =Math.Round( n * n / 48.0);
}
else
{
m = Math.Round((n + 3) * (n + 3) / 48.0);
}
Console.Write(m);
}
它实际上给了我一半的分数。
解决方案
原来问题是提问者应该处理n
高达 1_000_000 的值。但是对于以整数乘法形式完成的此类输入n * n
,会静默溢出并产生意外结果。
(奇怪的是,对于这些情况,它本来可以double
更早地切换到,比如说n * (n / 48.0)
or(double)n * n / 48.0
而不是n * n / 48.0
。)
您可以使用类似checked { /* statements here */}
or 的语法(在表达式内部)checked(n * n)
来获取异常,而不是固定宽度整数类型无法保存的有效位的静默丢失。
提问者通过切换到long
:
static void Main(string[] args)
{
long n = long.Parse(Console.ReadLine());
double m;
if (n % 2 == 0)
{
m = Math.Round(n * n / 48.0);
}
else
{
m = Math.Round((n + 3) * (n + 3) / 48.0);
}
Console.Write(m);
}
如果您有权访问 System.Numerics,则可以编写一个适用于更大输入的解决方案:
static void Main(string[] args)
{
BigInteger n = BigInteger.Parse(Console.ReadLine());
BigInteger m;
if (n % 2 == 0)
{
m = (n * n + 24) / 48;
}
else
{
m = ((n + 3) * (n + 3) + 24) / 48;
}
Console.Write(m);
}
我们使用整数除法/
,并且将分母的一半添加到分子的技巧确保正确舍入到最接近的值。
推荐阅读
- azure - 使用条件将 Blob 数据复制到 Azure 数据工厂中的 Sql 数据库
- angular - 如何在chartjs图表中绘制异步数据
- linux - 如何从 linux 链接器转储链接器库搜索路径。使用“制作”
- excel - Excel中的自动递增数字值
- javascript - 如何使用 Promise 和循环遍历 mongoose 集合
- kubernetes - k8s 相对于节点数动态设置副本数
- gradle - 如何在 Groovy 类中访问 build.gradle 中定义的额外属性?
- java - IBM Watson 语音到文本集成
- r - R - 带有ggplot2的climograph:更改降水值以适合第二轴
- c++ - 我的通用参考模板功能不起作用