编程介的小学生 2019-04-28 16:54 采纳率: 0.4%
浏览 211

多行计算包含的最大求和?如何利用C语言的程序的编写的办法?

Problem Description
We once did a lot of recursional problem . I think some of them is easy for you and some if hard for you.
Now there is a very easy problem . I think you can AC it.
We can define sum(n) as follow:
if i can be divided exactly by 3 sum(i) = sum(i-1) + i*i*i;else sum(i) = sum(i-1) + i;
Is it very easy ? Please begin to program to AC it..-_-

Input
The input file contains multilple cases.
Every cases contain only ont line, every line contains a integer n (n<=100000).
when n is a negative indicate the end of file.

Output
output the result sum(n).

Sample Input
1
2
3
-1

Sample Output
1
3
30

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-09 05:12
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    #include <stdio.h>
    
    int main() {
        int n;
        scanf("%d", &n);
        while (n != -1) {
            long long res = 0;
            int i = 1;
            while (i <= n) {
                res += i * i * i;
                i *= 3;
            }
            printf("%lld\n", res);
            scanf("%d", &n);
        }
        return 0;
    }
    

    这是一个简单的C语言程序,用于计算给定整数n的求和。对于每个整数n,程序将计算一个特定的表达式,并将其结果输出到屏幕上。这个表达式是根据给定的条件(如果n可以被3除尽,则sum(i) = sum(i-1) + i^3;否则sum(i) = sum(i-1) + i)来定义的。

    在循环中,程序逐个遍历从1到n的所有整数,并计算它们的立方并加到总和上。最后,程序读取下一个整数n,直到遇到-n为止,即输入文件结束时停止读取。

    注意:这段代码使用了scanf函数和printf函数来处理输入和输出。你需要确保你的环境中已经包含了这两个函数才能运行这段代码。

    评论

报告相同问题?