C 正确计算总和
C calculating sum correctly
本文关键字:计算 更新时间:2023-10-16
每次用户输入整数时,我都可以得到总和,直到输入负数或非整数。 问题是我的总和计算是关闭的。 即用户输入 1000;总和输出 1111,然后是用户输入 2000,加起来为 3333。任何建议都是值得赞赏的。我仍然会尝试我的编码。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer charactersn";
cout << "Enter another integer number: ";
}
return 0;
}
看起来您正在尝试输出一个整数,并在 1000 个边界处插入逗号。 即:1000000 将显示为 1,000,000。
在这种情况下,最简单的方法可能不涉及数学,而只是获取 int 的字符串表示(例如atoi()
)并对其进行计数。 从后面向前数三个字符,插入一个逗号,重复直到字符串用完为止。
字符串处理的细节留给读者作为练习 - 看起来这毕竟是他的家庭作业。 ;-)
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 计算缩放多边形的比例,得到给定的多边形面积
- 在C++中如何在没有pow的情况下进行基础计算
- 计算平均值,不包括上次得分
- 如何计算多映射中重复对的数量