如何编写这个 C++代码输入苹果迪伦

发布于 2024-12-28 15:15:30 字数 536 浏览 3 评论 0原文

我是计算机编程新手。我需要帮助来完成这项任务。我需要将这个简单的 C++ 源代码转换为苹果 dylan 代码。这是原始的数学陈述:

Task: Input an integer number n and output the sum: 1+22+32+...+n2. Use input validation for n to be positive.

我用 C++ 写了这段代码:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    if (n < 0) return 1;
    int sum = 0;
    int i = 0;
    while (i <= n) sum += i*i;
    cout << sum;
    return 0;
}

谁能帮我把这段代码写到 apple dylan 中?

最好的祝愿, 保罗

I'm new to computer programming. I need help with this task. I need to convert this simple C++ source code into apple dylan code. This is the original mathematical statement:

Task: Input an integer number n and output the sum: 1+22+32+...+n2. Use input validation for n to be positive.

I wrote this code in C++:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    if (n < 0) return 1;
    int sum = 0;
    int i = 0;
    while (i <= n) sum += i*i;
    cout << sum;
    return 0;
}

Can anyone help me to write this code into apple dylan?

Best wishes,
Paul

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烈酒灼喉 2025-01-04 15:15:30

这是一个递归解决方案:(

define method sumSquaresFromOne(n :: <integer>)
  if (n = 1)
    1
  else
    n *n + sumSquaresFromOne(n - 1)
  end
end method;

显然,它可以从 n < 1 的一些检查中受益。)

要运行该方法,您可以发出命令:

format-out("%d", sumSquaresFromOne(5))

其输出将为“55”(1 + 4 + 9 + 16 + 25 )。

您可以创建一个像这样的 main 方法:

define method main(appname, #rest arguments)
  format-out("Input an integer number n:")
  let n = read-line(*standard-input*)
  format-out("Sum of squares from t to %d is %d\n", n, sumSquaresFromOne(n))
  exit(exit-code: 0);
end method;

Here's a recursive solution:

define method sumSquaresFromOne(n :: <integer>)
  if (n = 1)
    1
  else
    n *n + sumSquaresFromOne(n - 1)
  end
end method;

(Obviously, it could benefit from some checking for n < 1.)

To run the method you would issue the command:

format-out("%d", sumSquaresFromOne(5))

The output of which would be "55" (1 + 4 + 9 + 16 + 25).

You could create a main method like this:

define method main(appname, #rest arguments)
  format-out("Input an integer number n:")
  let n = read-line(*standard-input*)
  format-out("Sum of squares from t to %d is %d\n", n, sumSquaresFromOne(n))
  exit(exit-code: 0);
end method;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文