Blue Bridge Cup practice - induction training 2

Topic three:

Problem description
evaluation 1 + 2 + 3 + ... + n is.
Input format: input comprises an integer n.
Output format: output line, including an integer representing the value 1 + 2 + 3 + ... + n is.
Sample input: 4
Sample Output: 10

Method One:
New Method for the number of columns and this is very easy to think of is to use a for loop. But this operation at when seeking a large number of columns and the number of timeouts and running can cause the phenomenon of numeric overflow.

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	int i, t=0, m=0;
	
	scanf("%d",&m);
	for(i = 1; i <= m; i++){
		t += i;
	}
	printf("%d",t);
	return 0;
}

Method Two:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	int m=0;
	int t=0;
	
	scanf("%d",&m);
	t = ((m+1)*m)/2;			//数列求和公式嘛
	printf("%d",t);
	
	return 0;
}

The easiest way is;

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	long long m=0, t=0;			//足够空间
	
	scanf("%d",&m);
	t = ((m+1)*m)/2;
	printf("%lld",t);
	
	return 0;
}

On - the importance of initialization of
very, very important! ! !

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/88535211