c语言4-13 求1到n的和


 

1、while语句

#include <stdio.h>

int main(void) { int i, sum = 0; puts("please input an integer."); do { printf("i = "); scanf("%d", &i); if (i <= 0) puts("the range of i is: > 0. "); } while (i <= 0); printf("the sum of 1 to %d is: ", i); while (i > 0) { sum += i; i--; } printf("%d\n", sum); return 0; }

 

2、while语句;

#include <stdio.h>

int main(void) { int i = 1, j, sum = 0; puts("please input an integer."); do { printf("j = "); scanf("%d", &j); if (j <= 0) puts("the range of j is: > 0 "); } while (j <= 0); printf("the sum of 1 to %d is: ", j); while (i <= j) { sum += i; i++; } printf("%d\n", sum); return 0; }

 

3、for语句

#include <stdio.h>

int main(void) { int i, sum = 0; puts("please input an integer."); do { printf("i = "); scanf("%d", &i); if (i <= 0) puts("the range of i is : > 0 "); } while (i <= 0 ); printf("the sum of 1 to %d is: ", i); for (i; i > 0; i--) { sum += i; } printf("%d\n", sum ); return 0; }

 

4、for语句

#include <stdio.h>

int main(void) { int i, j, sum = 0; puts("please input an integer."); do { printf("j = "); scanf("%d", &j); if (j <= 0) puts("the range of j is: > 0. "); } while (j <= 0); printf("the sum of 1 to %d is: ", j); for (i = 1; i <= j; i++) { sum += i; } printf("%d\n", sum); return 0; }

 

5、do语句

#include <stdio.h>

int main(void) { int i, sum = 0; puts("please input an integer."); do { printf("i = "); scanf("%d", &i); if (i <= 0) puts("the range of i is: > 0 "); } while (i <= 0); printf("the sum of 1 to %d is: ", i); do { sum += i; i--; } while (i > 0); printf("%d\n", sum); return 0; }

 

6、do语句

#include <stdio.h>

int main(void) { int i = 1, j, sum = 0; puts("please input an integer."); do { printf("j = "); scanf("%d", &j); if (j <= 0) puts("the range of j is: > 0 "); } while (j <= 0); printf("the sum of 1 to %d is: ", j); do { sum += i; i++; } while (i <= j); printf("%d\n", sum); return 0; }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM