在C++中分离数字
Separating Digits in C++
我正在编写C++书中的一个练习,我不知道如何修复它。我应该从用户那里获得一个int,并按照输入的顺序显示各个数字。例如,12345将显示1 2 3 4 5。7365将显示7 3 6 5。我已经编写了大部分代码,但有一个逻辑错误,我无法理解。这是我的代码:
int main()
{
int number = 0;
int digit = 0;
int temp = 0;
int counter = 0;
int sum = 0;
int divisor = 0;
cout << "Please enter a nonzero number.";
cin >> number;
cout << "nThe number you entered was " << number;
// Determine the number of digits
temp = number;
while (temp != 0)
{
temp = temp / 10;
counter++;
}
cout << "nThere are " << counter << " digits in your number.";
// Separate the digits
temp = number;
cout << "nSeparating the digitsn";
do
{
divisor = (pow(10.0, --counter));
digit = temp / divisor;
temp = temp % divisor;
cout << digit << " ";
sum = sum + digit;
}
while (counter != 0);
cout << "nThe sum of the number is " << sum;
return 0;
}
当我输入5555时,输出为5560。当我输入1234时,输出为1236。有人能帮我找出错误吗?
这里有一个版本:
// If the number is only one digit, print it.
// Otherwise, print all digits except the last, then print the last.
void digits(int x)
{
if (x < 10){
cout << x;
}
else{
digits(x / 10);
cout << " " << x % 10;
}
}
感谢大家的帮助:-)我的代码在另一个编译器中运行良好,所以我想这只是netbeans故障。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何解析小数分离器为结肠的数字的字符串表示:
- 从字符串中分离相同数字的序列
- C++简介:将字符串从文件行中的数字中分离出来,并对这些数字求和
- 在C++中分离数字
- 如何在C++中从数字中分离数字