解题思路:

  1. 首先,读取输入的商品种类数 n;
  2. 创建一个变量 total 来保存总金额,初始化为 0;
  3. 使用一个循环,循环 n 次,每次读取商品的单价和购买量;
  4. 将单价乘以购买量,得到该种商品的总金额,加到 total 上;
  5. 循环结束后,将 total 乘以 0.85,得到打折后的金额;
  6. 将打折后的金额转化为一位小数,且舍去多余的小数位;
  7. 输出打折后的金额。

代码示例:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  int n;
  double total = 0;
  cin >> n;
  for (int i = 0; i < n; i++) {
    double price, quantity;
    cin >> price >> quantity;
    total += price * quantity;
  }
  total *= 0.85;
  cout << fixed << setprecision(1) << total << endl;
  return 0;
}

代码解释:

  • #include <iostream>#include <iomanip> 分别用于输入输出和格式化输出。
  • using namespace std; 用于简化代码,避免每次使用 std:: 前缀。
  • int main() 是程序的入口函数。
  • int n; 定义变量 n 用于存储商品种类数。
  • double total = 0; 定义变量 total 用于存储总金额,并初始化为 0。
  • for (int i = 0; i < n; i++) 循环读取商品的单价和购买量。
  • double price, quantity; 定义变量 pricequantity 分别用于存储单价和购买量。
  • cin >> price >> quantity; 读取输入的单价和购买量。
  • total += price * quantity; 将单价乘以购买量,得到该种商品的总金额,加到 total 上。
  • total *= 0.85;total 乘以 0.85,得到打折后的金额。
  • cout << fixed << setprecision(1) << total << endl;total 格式化为一位小数并输出。
  • return 0; 表示程序正常退出。

运行结果:

输入:

3
3.00 2
17.95 1
0.10 1

输出:

20.4

原文地址: https://www.cveoy.top/t/topic/phaG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录