介绍
加法、减法、乘法和除法等算术运算是编程中的基本操作。在这个实验中,我们将向你展示如何编写一个 C 程序来执行基本的算术运算,以及 C 语言如何处理类型转换。
加法、减法、乘法和除法等算术运算是编程中的基本操作。在这个实验中,我们将向你展示如何编写一个 C 程序来执行基本的算术运算,以及 C 语言如何处理类型转换。
在开始之前,请确保你的机器上已经安装了 C 编译器。打开你的文本编辑器,在 ~/project/ 目录下创建一个名为 "main.c" 的新文件。
让我们从包含 stdio.h 头文件并编写主函数开始:
#include<stdio.h>
int main()
{
return 0;
}
使用 scanf() 函数让用户输入两个整数。声明变量 int a 和 int b 来存储这些整数。
#include<stdio.h>
int main()
{
int a, b;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
return 0;
}
现在,让我们在不进行类型转换的情况下执行基本的算术运算。声明变量 add、subtract、multiply 和 divide 来存储算术运算的结果。
#include<stdio.h>
int main()
{
int a, b, add, subtract, multiply;
float divide;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
add = a + b;
subtract = a - b;
multiply = a * b;
divide = a / b;
printf("Addition of the numbers = %d\n", add);
printf("Subtraction of 2nd number from 1st = %d\n", subtract);
printf("Multiplication of the numbers = %d\n", multiply);
printf("Dividing 1st number from 2nd = %f\n", divide);
return 0;
}
C 语言会隐式处理类型转换。然而,我们也可以在程序中显式处理它。让我们编写一个 C 程序,执行带有类型转换的基本算术运算。
声明变量 add、subtract、multiply、divide 和 remainder 来存储算术运算的结果。
#include<stdio.h>
int main()
{
int a, b, add, subtract, multiply, remainder;
float divide;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
add = a + b;
subtract = a - b;
multiply = a * b;
divide = a / (float)b;
remainder = a % b;
printf("Addition of the numbers = %d\n", add);
printf("Subtraction of 2nd number from 1st = %d\n", subtract);
printf("Multiplication of the numbers = %d\n", multiply);
printf("Dividing 1st number from 2nd = %f\n", divide);
printf("Remainder on Dividing 1st number by 2nd is %d\n", remainder);
return 0;
}
保存 main.c 文件。打开终端并进入保存文件的 ~/project/ 目录,使用以下命令编译程序:
gcc -o main main.c
这将生成一个名为 main 的可执行文件。使用以下命令运行程序:
./main
通过输入两个整数来测试程序,并检查程序是否按预期执行算术运算。
#include<stdio.h>
int main()
{
int a, b, add, subtract, multiply, remainder;
float divide;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
add = a + b;
subtract = a - b;
multiply = a * b;
divide = a / (float)b;
remainder = a % b;
printf("Addition of the numbers = %d\n", add);
printf("Subtraction of 2nd number from 1st = %d\n", subtract);
printf("Multiplication of the numbers = %d\n", multiply);
printf("Dividing 1st number from 2nd = %f\n", divide);
printf("Remainder on Dividing 1st number by 2nd is %d\n", remainder);
return 0;
}
在这个实验中,我们学习了如何编写一个 C 程序来执行基本的算术运算,以及 C 语言如何处理类型转换。我们演示了如何在不进行类型转换和进行类型转换的情况下执行基本的算术运算。最后,我们编译并运行了程序以测试其功能。