首页 > 解决方案 > 从循环中获取总值

问题描述

我在解决代码时遇到问题;我试图从每个循环中获取一个总值,但是每次循环发生时,它都会用新的值覆盖以前的值。

不同的解释:
我需要循环继续为前一个 pow 添加值,所以如果我为 atk 输入 3,它应该添加1st Loop [50(Base)+50] + 2nd Loop [50(Base)+50+50], 3rd Loop [50(Base)+50+50+50],然后我希望循环总计最后的所有值450。希望我解释得对。```

我对 C++ 很陌生,我希望你能教我怎么做。

我尝试过使用 for、do while 和 if。

//variables
int base=50; //base damage
int up=50;  //damage increase per hit
int atk=0;  //number of attacks
int pow=0;  //total attack power

scanf("%d", &atk); //input number of attacks

while (atk >= 1) //number of attacks loop
{
    pow += atk * up + base;  //total attack power calculation
    atk--; //every time attack happens, subtract 1 from remaining attacks
}
printf("%d\n", pow); //total attack power

我希望编译后的代码看起来像这样。我从我的作业问题中复制粘贴了这个示例输出。

Explanation
For Sample Test Case 3, damage for every hit by Templor Assasson :
• Hit 1 : 100 + 0 = 100
• Hit 2 : 100 + 50 = 150
• Hit 3 : 100 + 100 = 200
Thus, total damage of Templor Assasson is 450.

问题截图

标签: c++

解决方案


  1. 您缺少 100 * 基数(初始攻击次数,例如 - 3)。
  2. 未初始化的 pow,使用int pow = 0;
  3. 你应该加起来(atk * up)。正如评论中提到的,例如 -pow += atk * up;
  4. 您正在添加(n * up) + (n-1 * up) + .... + (1 * up)特别仔细查看示例的值n。提示 - 将您的 (n * base) 的第一轮值与示例进行比较。
  5. 一旦你解决了它,你就会得到一个额外的琐事。您可以在一行中完成,无需任何循环

推荐阅读