题解
【入门】种蔬菜
1 条题解
-
0
解题思路
四种蔬菜共占地 80 平方米,已知番茄、黄瓜、韭菜各占 a%、b%、c%,求四种蔬菜各自的面积。
思路:
- 把百分数转成小数:35% = 35 ÷ 100 = 0.35
- 每种蔬菜的面积 = 百分比 × 总面积 80
- 萝卜的面积 = 总面积 - 其他三种的面积
- 保留 1 位小数输出
怎么解析百分数? 输入的百分数如 35%,用 stoi 可以把 35 提取出来(stoi 会自动跳过非数字字符 %)。
举例:35% 20% 21%
- 番茄 = 0.35 × 80 = 28
- 黄瓜 = 0.20 × 80 = 16
- 韭菜 = 0.21 × 80 = 16.8
- 萝卜 = 80 - 28 - 16 - 16.8 = 19.2
参考代码
#include <iostream> #include <iomanip> #include <string> using namespace std; int main() { string s1, s2, s3; cin >> s1 >> s2 >> s3; double a = stoi(s1) * 1.0 / 100; // 转小数 double b = stoi(s2) * 1.0 / 100; double c = stoi(s3) * 1.0 / 100; double x1 = a * 80; // 番茄 double x2 = b * 80; // 黄瓜 double x3 = c * 80; // 韭菜 double x4 = 80 - x1 - x2 - x3; // 萝卜 cout << fixed << setprecision(1) << x1 << " "; cout << fixed << setprecision(1) << x2 << " "; cout << fixed << setprecision(1) << x3 << " "; cout << fixed << setprecision(1) << x4; return 0; }复杂度分析
- 时间复杂度:O(1)
- 空间复杂度:O(1)
- 1