首页 > 其他 > 详细

C学习if条件判断和for循环

时间:2015-04-07 13:50:24      阅读:238      评论:0      收藏:0      [点我收藏+]

通过学习if条件判断和for循环之后,做了一个实例。实现的实例都在代码中有详细的注释。

#include <stdio.h>

/******************************************************
 * 输入一个数字n,求
 * 1+1+2+1+2+3+1+2+3+4...+n
 * 该实例主要为了练习if语句和for语句
 ******************************************************/
int main(void)
{
    printf("%s\n","Please enter the number n:");

    int n;
    int count = 0;

    scanf("%d",&n);

    if(n <= 0){  //如果输入的数字n小于0,则提示错误
        printf("%s\n","The number you entered is too small!!");
        return -1;
    }

    int i;
    for(i = 1;i <= n;i++){
        int j;
        for(j = 1;j <= i;j++){
            count += j;
        }
    }

    printf("The count of the number n = %d.\n",count);

    return 0;
}

在C语言中,不像C++,要求比较高,是不能这样使用的。

for(int i = 0;i < 4;i++)

这样在编译的时候就会报这样的错误

/**
 * error:‘for‘ initial declaration are 
 * only allowed in C99 mod
 */

所以在C语言中,最好是提前声明一下变量。

C学习if条件判断和for循环

原文:http://blog.csdn.net/hongbochen1223/article/details/44918939

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!