例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", sum);
return 0;
}
例1.3求两个整数中的较大者
#include<stdio.h>
int main()
{
int max(int x, int y);
int a, b, c;
scanf("%d,%d", &a, &b);
c = max(a, b);
printf("max = %d\n", c);
return 0;
}
int max(int x, int y)
{
int z;
if(x > y)
{
z = x;
}
else
{
z = y;
}
return (z);
}
改:
#include<stdio.h>
int main()
{
int max(int x, int y);
int a, b, c;
scanf("%d%d", &a, &b);
c = max(a, b);
printf("max = %d\n", c);
return 0;
}
int max(int x, int y)
{
int z;
if(x > y)
{
z = x;
}
else
{
z = y;
}
return (z);
}
习题
5.请参照本章例题,编写一个C程序,输出以下信息
#include<stdio.h>
int main()
{
printf("******************************\n\n");
printf("Very Good!\n\n");
printf("******************************\n");
return 0;
}
6.编写一个C程序,输出a,b,c三个值,输出其中最大值。
#include<stdio.h>
int main()
{
int a, b, c,max;
printf("please input a, b, c:\n");
scanf("%d, %d, %d", &a, &b, &c);
max = a;
if(max < b)
{
max = b;
}
if(max < c)
{
max = c;
}
printf("The largest number is %d\n", max);
return 0;
}
改
#include<stdio.h>
int main()
{
int a, b, c,max;
printf("please input a, b, c:\n");
scanf("%d%d%d", &a, &b, &c);
max = a;
if(max < b)
{
max = b;
}
if(max < c)
{
max = c;
}
printf("The largest number is %d\n", max);
return 0;
}
例2.18将例2.16表示的算法(求5!)用C语言表示。
#include<stdio.h>
int main()
{
int i, t;
t = 1;
i = 2;
while(i <= 5)
{
t = t*i;
i = i+1;
}
printf("%d\n", t);
return 0;
}
例2.19将例2.17表示的算法(求多项式1-1/2+1/3-1/4+…+1/99-1/100的值)用C语言表示。
#include<stdio.h>
int main()
{
int sign = 1;
double deno = 2.0, sum = 1.0, term;
while(deno <= 100)
{
sign = -sign;
term = sign/deno;
sum =sum +term;
deno =deno + 1;
}
printf("%f\n", sum);
return 0;
}
例3.1有人用温度计测量出华氏法表示的温度(如69°F),今要求把它转换为摄氏法表示的温度(如20℃)。
#include<stdio.h>
int main()
{
float f, c;
f = 64.0;
c = (5.0 / 9) * (f - 32);
printf("f = %f\nc = %f\n", f, c);
return 0;
}
例3.2计算存款利息。有1000元,想存一年。有3种方法可选:(1)活期,年利率为rl;(2)一年期定期,年利率r2。(3)存两次半年定期,年利率r3。请分别计算出一年后按3种方法所得到的本息和。
#include<stdio.h>
int main()
{
float p0 = 1000, r1 = 0.0036, r2 = 0.0225, r3 = 0.0198, p1, p2,p3;
p1 = p0 * (1 + r1);
p2 = p0 * (1 + r2);
p3 = p0 * (1 + r3/2) * (1 + r3/2);
printf("p1 = %f\np2 = %f\np3 = %f\n", p1, p2, p3);
return 0;
}
例3.3给定一个大写字母,要求用小写字母输出。
#include<stdio.h>
int main()
{
char c1, c2;
c1 = 'A';
c2 = c1 + 32;
printf("%c\n", c2);
printf("%d\n", c2);
return 0 ;
}
微信公众号“计算机基础学”关注我哦。