如果一个人每天的工资是一分钱,那么随着时间的推移,他会挣多少钱(IT专业的学生除外)

C++ program on how much a person would earn over time if salary is one penny per day (Not an IT student)

本文关键字:IT 多少 每天 一个人 一分钱 时间 如果      更新时间:2023-10-16

我有一个项目要写一个程序,计算一个人在一段时间内的收入,如果他或她的工资是第一天一便士,第二天两便士,然后每天翻一番。程序应该询问用户的天数。显示一个表,显示每天的工资,然后在期末显示总工资。输出应该以美元金额显示,而不是便士的数目。

输入验证:工作天数不接受小于1的数字。

这是我的代码到目前为止,我似乎不能让它正常工作(不是一个学生)

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip.h>
int main()
{
    int days;
    double pennies = 0.01;
    double total = 0.0;
    double fixed;
    double showpoint;
    cout << "For how many days will the pay double?";
    cin >> days;
    cout << endl << "Day    Total Payn";
    cout << "------------------------n";
    for (int count = 1; count <= days; count++)
    {
        cout << count << "tt$t" << (pow(2, pennies)) << endl;
    }
    cout << setprecision(2) << fixed << showpoint;
    cout << "--------------------------------n";
    cout << "Total  $t" << total << endl;
    getch();
    return 0;
}

我已经尽力解释我所做的更改,但如果您需要了解更多,请询问

// Headers for standard library features don't have .h on the end (normally)
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip>
int main()
{
    int days = 0;
    // double pennies = 0.01; Not needed.
    double total = 0.0;
    // If you don't initialise variables it will cause a crash or undefined behaviour.
    // double fixed;
    // double showpoint;
    while (days < 1)    // This prevents negative or 0 day contracts.
    {
        // You need to use the full name to cout or that abomination of a command using namespace std
        std::cout << "For how many days will the pay double?";
        std::cin >> days;
    }
    std::cout << std::endl << "Day    Total Payn";
    std::cout << "------------------------n";
    // looping from 0 while less than days is more "normal".
    for (int count = 0; count < days;  count++)
    {
        double payForTheDay = (pow(2, count));
        std::cout << count << "tt$t" << payForTheDay << std::endl;
        total += payForTheDay;  // You need to increment the total.
    }
    // Not sure what this is about
    // std::cout << std::setprecision(2) << fixed << showpoint;
    std::cout << "--------------------------------n";
    std::cout << "Total  $t" << total << std::endl;
    getch();
    return 0;
}

尝试将(pow(2, pennies))替换为(pennies * pow(2, (count - 1)))

指出:

  1. pennies不应该被命名为dollars吗?

  2. 要计算total,只需将其增加到每天的日工资(例如在输出每一行表的循环中)。

看一下问题的基础。它基本上是一个几何级数。

在等比数列中n个数的和为;

Sn=a1((1-r^n)/(1-r))
[a1=first element(in your case 1);r=2(in this case)]

使用公式得到n天的便士数。现在把它转换成美元价值。

如果你需要完整的代码注释在这里

很晚了,但在我看来,对2^n使用按位移位是最好的方法。它是快速和容易使用。

int days; // = amount of days for payment;
// Add input/output logic
if (days<1) {
    // Do invalid input logic
}
// Use long long if days>31
for (int K=0; K<days; K++)
    cout<<"Day "<<K<<": "<<(1<<K)<<"n;

这里1<<K是2^K

或者,您可以使用一个变量来保存支付每次迭代移动1