c++ - 从循环中获取总值
问题描述
我在解决代码时遇到问题;我试图从每个循环中获取一个总值,但是每次循环发生时,它都会用新的值覆盖以前的值。
不同的解释:
我需要循环继续为前一个 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.
解决方案
- 您缺少 100 * 基数(初始攻击次数,例如 - 3)。
- 未初始化的 pow,使用
int pow = 0;
- 你应该加起来(atk * up)。正如评论中提到的,例如 -
pow += atk * up;
- 您正在添加
(n * up) + (n-1 * up) + .... + (1 * up)
特别仔细查看示例的值n
。提示 - 将您的 (n * base) 的第一轮值与示例进行比较。 - 一旦你解决了它,你就会得到一个额外的琐事。您可以在一行中完成,无需任何循环
推荐阅读
- python - 从嵌套字典中获取具有最大值的键
- python - 使用 Python 将字符串(2019 年 6 月 6 日上午 9:29:29)转换为日期时间(YMD H:M:S) -
- wordpress - 无法使用虚拟主机访问 wp-admin
- python-3.x - 为什么我在第一行出现语法错误?
- msbuild - 如何将 NuGet contentFiles 提取到特定目录?
- typescript - 由于 google-cloud 包中的问题,TSC 构建失败,
- java - 如何为 Google Cloud API 生成访问令牌?
- java - 如何从网络 selenium+Java 获取查询字符串参数
- windows - Windows 命令删除现有目录并创建新目录
- powerbi - 在 Power BI Desktop DAX 论坛中应用筛选器的问题