HDOJ杭电OJ 1001题

题目

Problem Description
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + … + n.

Input
The input will consist of a series of integers n, one integer per line

Output
For each case, output SUM(n) in one line, followed by a blank line. You may assume the result will be in the range of 32-bit signed integer.

Sample Input
1 100
Sample Output
1 5050

错误回答

#include <stdio.h>
int main(void)
{
	int a[1000];
	int n, m, len, i, j, sum = 0;
	scanf_s("%d", &len);
	for (i = 0;i < len;i++)
	{
		scanf_s("%d", &a[i]);
	}
	printf("%d\n", len);
	for (i = 0; i < len; i++)
	{
		for (j = 1; j <= a[i]; j++)
		{
			sum = sum + j;
		}
		printf("%d\n", sum);
	}
	return 0;
}

错误原因

1.没理解对题目,以为是先输入行数,每行再输入数据之后,再输出每行的结果(即使如此也没有作对,不会定义n个数据的数组!)
2.过于麻烦,代码繁冗

大佬代码

#include<stdio.h>
int main() {
    for (int n, k, t; ~scanf_s("%d", &n);k=(n>>1),t=(1+n)*(n>>1),printf("%d\n\n", n%2==0?t:t+k+1));
    return 0;
}

这个for循环中冒号(:)问号(?)句式的用法可以看我上一篇博客,while(scanf)的用法也在之前的文章里说过,个人感觉跟这个是类似的,关于for(判断)中scanf的用法我并没有找到。希望懂的可以在评论区补充一下

1.用n>>1代替n/2可以提高执行效率(记住就行)
2.n是整数,为了避免漏项(n/2+1),使用 n%2==0?t:t+k+1.
冒号(:)问号(?)句式

如有数据溢出等问题出现,参考大佬原文
原文

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值