c++求解!。,、‘;’

img


c++编程题
能打一下吗
老是超出时间限制

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

int main() {
    float r, a, b;
    int years = 0;
    cin >> r >> a >> b;

    float target = a + (a * r / 100);  // 第一年的目标金额
    while (target < b) {
        a = target;
        target = a + (a * r / 100);  // 计算下一年的目标金额
        years++;
    }

    cout << years << " " << fixed << setprecision(2) << target << endl;

    return 0;
}

优化点,后加加改成前加加
cout 不然就用 printf 吧

用scanf替换cin输入,试试,再有可能就是解题思路错了

【以下回答由 GPT 生成】

优化方案: 1. 将浮点数的运算转化为整数的运算,因为整数运算比浮点数运算更快。 2. 将浮点数的乘法换成整数的乘法。 3. 将浮点数的除法转化为整数的除法,使用取整运算符/而不是实数除法运算符/。 4. 将浮点数的加法转化为整数的加法。

以下是优化后的代码:

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

int main() {
    int r, a, b;
    int years = 0;
    cin >> r >> a >> b;

    int target = a + (a * r / 100); // 第一年的目标金额
    while (target < b) {
        a = target;
        target = a + (a * r / 100); // 计算下一年的目标金额
        years++;
    }

    cout << years << " " << fixed << setprecision(2) << target / 100.0 << endl;

    return 0;
}

通过将浮点数运算转换为整数运算,可以提高程序的性能,并减少超时的可能性。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^