使用C语言解决盈亏问题
给定某种产品的成本价 (cp) 和售价 (sp),我们的任务是使用 C 语言程序找出获得的利润或遭受的损失。如果获得利润,则打印“利润”及其金额;如果遭受损失,则打印“损失”及其相应金额;如果没有利润也没有损失,则打印“无利润也无损失”。
为了找出利润或损失,我们通常查看售价 (sp)(某物出售的价格/金额)或成本价 (cp)(某物购买的价格)。如果成本价 (cp) 高于售价 (sp),则认为有损失,其差额即为遭受的总损失。如果售价 (sp) 高于成本价 (cp),则认为获得利润,其差额即为总利润。
输入 − cp = 149, sp = 229
输出 − 利润 80
说明 − 售价 (sp) > 成本价 (cp),所以利润为 sp-cp=80
输入 − cp = 149, sp = 129
输出 − 损失 20
说明 − 成本价 (cp) > 售价 (sp),所以损失为 cp-sp=20
下面使用的解决问题的方法如下:
输入成本价和售价
检查成本价是否 > 售价,如果是,则为损失,找到差额并返回结果。
检查售价是否 > 成本价,如果是,则为利润,找到差额并返回结果。
如果售价 == 成本价,则既无利润也无损失。
算法
Start In function int Profit(int cp, int sp) Step 1→ Return (sp - cp) In function int Loss(int cp, int sp) Step 1→ Return (cp - sp) In function int main() Step 1→ Declare and initialize cp = 5000, sp = 6700 Step 2→ If sp == cp then, Print "No profit nor Loss" Step 3→ Else if sp > cp Print Profit Step 4→ Else Print Loss Stop
示例
#include <stdio.h>
//Function will return profit
int Profit(int cp, int sp){
return (sp - cp);
}
// Function will return Loss.
int Loss(int cp, int sp){
return (cp - sp);
}
int main(){
int cp = 5000, sp = 6700;
if (sp == cp)
printf("No profit nor Loss
");
else if (sp > cp)
printf("%d Profit
", Profit(cp, sp));
else
printf("%d Loss
", Loss(cp, sp));
return 0;
}输出
如果运行上述代码,将生成以下输出:
1700 Profit
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP