简体   繁体   English

c语言系列之和

[英]Sum of series in c language

Sum of series using c language用c语言进行系列求和

sample input : 12 15 sample output : 54样本输入:12 15样本输出:54

sample input : 1 100 sample output : 5050样本输入:1 100样本输出:5050

#include <stdio.h>

int main(){
    
    int a, b;
    
    scanf("%d %d", &a, &b);
    printf("%lld",a*(b+1)/2);
    
    return 0;
}

The %lld format specifier is used to print a long long int . %lld格式说明符用于打印long long int The argument you're passing has type int .您传递的参数类型为int Mismatching format specifiers triggers undefined behavior , which in this case will likely result in output you don't expect.不匹配的格式说明符会触发未定义的行为,在这种情况下可能会导致您不期望的输出。

To print an int use %d .要打印int使用%d

printf("%d",a*(b+1)/2);

Your formula: a*(b+1)/2 is wrong你的公式: a*(b+1)/2是错误的

Try:尝试:

((b+1)*b - a*(a-1))/2

(assuming that b >= a and a >= 0 ) (假设b >= aa >= 0

So the program could be:所以程序可以是:

#include <stdio.h>

int main(void)
{
    int a, b;
    
    if (scanf("%d %d", &a, &b) != 2) exit(1);
    if (a < 0) exit(1);
    if (b < a) exit(1);
    printf("%d", ((b+1)*b - a*(a-1))/2);
    
    return 0;
}

Note: The formula can be updated to handle negative values but I'll leave that to OP注意:可以更新公式以处理负值,但我会将其留给 OP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM