计算简单利息程序

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何编写一个 C 程序来计算给定本金、利率和期限的简单利息。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123332{{"`计算简单利息程序`"}} c/data_types -.-> lab-123332{{"`计算简单利息程序`"}} c/operators -.-> lab-123332{{"`计算简单利息程序`"}} c/math_functions -.-> lab-123332{{"`计算简单利息程序`"}} c/user_input -.-> lab-123332{{"`计算简单利息程序`"}} c/output -.-> lab-123332{{"`计算简单利息程序`"}} end

初始化变量

声明并初始化变量 principal_amtratesimple_interesttime,分别作为浮点型和整型,如下所示:

#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 显示输出等基本概念。恭喜你完成了本次实验!

您可能感兴趣的其他 C 教程