/*=========================================
* Copyright (c) 2020, 逐风墨客
* All rights reserved.
*
* 文件名称:study_accpn.c
* 运行环境:Linux系统
* 功能描述:输入一个大于0的任意整数,
计算1-2+3-4+5-6+7......+n!
=========================================*/
#include <stdio.h>
#include <stdlib.h>
long get_acc(long n);
int main(void)
{
long lNum;
long lSum;
printf("\nPlease enter a number(1~n) to accumulate : n = ");
scanf("%ld", &lNum);
lSum = get_acc(lNum);
printf("1-2+3-4+5-6+7......+%ld = %ld", lNum, lSum);
return 0;
}
/******************************************
* 函数介绍:long get_acc(long n)
* 输入参数:n-最大范围的累加数值
* 输出参数:无
* 返回值:1-2+3-4+5-6+7......+n 的累加值
******************************************/
long get_acc(long n)
{
if (n <= 0)
{
printf("error : n must > 0!\n");
exit(1);
}
if (0 == n%2)
{
return (n / 2) * (-1);
}
else
{
return (n / 2) * (-1) + n;
}
}
程序运行结果: