第一章节 程序设计和C语言
1.4 最简单的C语言程序
例1.1 要求在屏幕上输出以下一行信息:
This is a C program.
#include<stdio.h>
int main()
{
printf("This is a C program.\n");
return 0;
}
运行结果如下:
例1.2求两个整数之和。
#include<stdio.h>
int main()
{
int a,b,sum;
a=123;
b=456;
sum=a+b;
printf("sum is %d\n");
return 0;
}
运行结果如下:
例1.3求两个整数中的较大者。
#include<stdio.h>
int main()
{
int max(int x,int y);
int a,b,c;
scanf("%d,%d,%d",&a,&b,&c);
c=max(a,b);
printf(max=%d\n",c);
return 0;
}
int max(int x,int y)
{
int z;
if(x>y)z=y;
else z=y;
return (z);
}
运行结果如下:
课后题及答案:
1.编写一个C程序,运行时输出:Hello World!
#include<stdio.h>
int main()
{
printf("hello World!\n");
return 0;
}
运行结果如下:
2.编写一个C程序,运行时输出以下图形:
*****
*****
*****
*****
#include<stdio.h>
int main()
{
printf("*****\n");
printf(" *****\n");
printf(" *****\n");
printf(" *****\n");
return 0;
}
运行结果如下:
3.编写一个C程序,运行时输入a,b,c三个值,输出其中值最大者。
#include<stdio.h>
int main()
{
int a,b,c,max;
printf("请输入三个值:")
scanf("%a%b%c",&a&b&c);
if(a>b)
{
if (a>c)
{
printf("max=%d\n",a);
}
else
{
printf("max=%d\n",c);
}
}
else
{
if(b>c)
{
printf("max=%d\n",b);
}
else
{
printf("max=%d\n",c);
}
}
return 0;
}
运行结果如下: