Bài thực hành 5
Hàm
Bài 1: Chạy chương trình sau: (chương trình sử dụng một hàm tính lập phương của một
số)
#include <stdio.h>
long cube(long x);
long input, answer;
main()
{
printf("Enter an integer value: ");
scanf("%d", &input);
answer = cube(input);
printf("\nThe cube of %ld is %ld.\n", input, answer);
return 0;
}
long cube(long x)
{
long x_cubed;
x_cubed = x * x * x;
return x_cubed;
}
Bài 2:
Chạy chương trình sau để thấy sự khác nhau giữa đối số và tham số
#include <stdio.h>
float x = 3.5, y = 65.11, z;
float half_of(float k);
main()
{
/* Ở lời gọi này, x là đối số cho hàm half_of(). */
z = half_of(x);
printf("Gia tri cua z = %f\n", z);
printf("\n Trong ham demo(), x = %d and y = %d.", x, y);
}
Kết quả chạy chương trình:
Truoc khi goi demo demo(), x = 1 and y = 2.
Trong demo(), x = 88 and y = 99.
Sau khi goi demo(), x = 1 and y = 2.
Bài 4: Sử dụng câu lệnh trả lại nhiều giá trị trong một hàm
#include <stdio.h>
int x, y, z;
int larger_of( int , int );
main()
{
puts("Nhap vao hai so nguyen khac nhau: ");
scanf("%d%d", &x, &y);
z = larger_of(x,y);
printf("\nGia tri lon hon la %d.", z);
return 0;
}
int larger_of( int a, int b)
{
if (a > b)
return a;
else
return b;
}
Kết quả chạy chương trình:
Nhap vao hai so nguyen:
200 300
Gia tri lon hon la 300.
Nhap vao hai so nguyen: