连续整数的平方根

时间:2018-07-11 17:23:21

标签: c# math square-root

This image is an exercise for our algorithm lab.

为什么我会收到错误的答案?这是我的代码:

glReadPixels

2 个答案:

答案 0 :(得分:3)

对于每个整数// New stuff var context = new PrincipalContext(ContextType.Domain, "mydomain.com"); var properties = new[] { "cn", "name", "distinguishedname", "surname", "title", "displayname" }; var i = 0; var now = DateTime.Now; // you should have done this BEFORE setting `context`. ,平方根应应用于到目前为止的总和,而不仅仅是当前的i

i

答案 1 :(得分:0)

这里的问题是您每次都添加n的平方根。 n的值是在循环之前分配的,永远不会更改。您需要每次增加i + total的平方根,而不是n的平方根:

// My input for testing was 13.
int n = int.Parse(Console.ReadLine());
double total = 0;
for (int i = n; i > 1; i -=4)
    total = Math.Sqrt(total + i);

Console.WriteLine($"Total: {Math.Sqrt(++total)} = 1.980.");
Console.ReadKey();

随时查看pre and post increment/decrement之间的区别。

int i = 1;
int x = i++; //x is 1, i is 2
int y = ++i; //y is 3, i is 3