第一章 程序设计和C语言 例题

作者在 2011-09-26 11:02:37 发布以下内容

例1.1

/*
时间:2011年9月26日10:22:35
题目:例1.1,要求在屏幕上输出以下一行信息 This is a c program.
*/
# include <stdio.h>        //stdio 是 standard Input & Output的缩写
int main()            //main是函数的名字,每个C语言都必须有1个main函数
{                    //函数体要由花括号括起来
    printf("This is a c program.\n");
    printf("//This is a c program.\n");        //字符串中//和/*不作为注释符号,只当做字符串的一部分    
    return 0;
}
/*
在VC++6.0中的输出结果为:
————————————
This is a c program.
//This is a c program.
Press any key to continue
————————————
*/

例1.2

/*
时间:2011年9月26日11:12:15
题目:例1.2 求两个整数之和
*/
# include <stdio.h>
int main()
{
    int a,b,sum;        //程序声明部分,定义a、b、sum为整形变量
    
    a = 123;            //赋值
    b = 456;
    sum = a+b;
    printf("sum is %d\n",sum);    //输出结果

    return 0;
}

/*
在VC++6.0中的输出结果为:
————————————
sum is 579
Press any key to continue
————————————
*/

例1.3

/*
时间:2011年9月26日11:23:21
题目:例1.3 求两个整数中的较大者
*/
# include <stdio.h>

int main()
{
    int max(int x,int y);    //对被调函数max的声明,缺少声明会报错 error C2065: 'max' : undeclared identifier
    int a,b,c;
    printf("Input 2 numbers\n");
    scanf("%d %d", &a,&b);        //从键盘输入两个整数,送到变量a和b的地址处,然后分别把这两个整数赋值给变量a和b
    c = max(a,b);        //函数调用,将实参a和b的值分别传送给函数max的形参x和y,执行max函数,然后把max函数的返回值赋值给变量c
    printf("The max is %d\n",c);
    return 0;
}

int max(int x,int y)        //被调函数,用来求两个整数中的较大者
{
    int z;
    if (x>y)        //将x,y中较大的那个赋值给z
        z = x;
    else
        z = y;
    return (z);        //将z的值作为函数max的函数值,返回给调用max函数的函数
}
/*
在VC++6.0中的输出结果为:
————————————
Input 2 numbers
8 5
The max is 8
Press any key to continue
————————————
*/
《C程序设计》学习 | 阅读 1372 次
文章评论,共0条
游客请输入验证码
最新评论