介绍
在本实验中,你将学习如何编写一个 C 程序来计算给定本金、利率和期限的简单利息。
在本实验中,你将学习如何编写一个 C 程序来计算给定本金、利率和期限的简单利息。
声明并初始化变量 principal_amt
、rate
、simple_interest
和 time
,分别作为浮点型和整型,如下所示:
#include <stdio.h>
int main()
{
float principal_amt, rate, simple_interest;
int time;
}
使用 scanf
从用户处获取本金金额、利率(以百分比表示)和期限(以年为单位):
printf("Enter the value of principal amount, rate and time\n\n\n");
scanf("%f%f%d", &principal_amt, &rate, &time);
使用 %f
格式说明符读取 float
类型的输入,使用 %d
读取 integer
类型的输入。
使用以下公式计算简单利息:
Simple Interest = (principal_amt * rate * time) / 100
使用以下代码计算简单利息:
simple_interest = (principal_amt*rate*time)/100.0;
使用 printf
函数将输出文本和变量打印到控制台。
printf("\n\n\t\t\tAmount = Rs.%7.3f\n ", principal_amt);
printf("\n\n\t\t\tRate = Rs.%7.3f\n ", rate);
printf("\n\n\t\t\tTime = %d years \n", time);
printf("\n\n\t\t\tSimple Interest = Rs.%7.3f\n ", simple_interest);
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
使用 %7.3f
将输出格式化为 7 位数字,其中包含小数点后 3 位。
将步骤 1-4 的代码复制到 ~/project/main.c
文件中的 main
函数中,如下所示:
#include <stdio.h>
int main()
{
printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
float principal_amt, rate, simple_interest;
int time;
printf("Enter the value of principal amount, rate, and time\n\n\n");
scanf("%f%f%d", &principal_amt, &rate, &time);
// considering rate is in percentage
simple_interest = (principal_amt*rate*time)/100.0;
// usually used to align text in form of columns in table
printf("\n\n\t\t\tAmount = Rs.%7.3f\n ", principal_amt);
printf("\n\n\t\t\tRate = Rs.%7.3f\n ", rate);
printf("\n\n\t\t\tTime= %d years \n", time);
printf("\n\n\t\t\tSimple Interest = Rs.%7.3f\n ", simple_interest);
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}
使用 C 编译器编译并运行程序。程序将提示用户输入本金金额、利率和期限,然后显示计算出的简单利息。
在本实验中,你学习了如何使用变量、用户输入和简单利息公式编写一个 C 程序来计算简单利息。你涵盖了声明和初始化变量、使用 scanf
获取用户输入以及使用 printf
显示输出等基本概念。恭喜你完成了本次实验!