C++ 中的数字计数器
Digits counter in c++
正如标题所说,我必须找出给定数字中的位数。这是我的代码,当数字超过 10 时,它给我的结果为 0Visual Studio Pro 2012 中的编程
法典:
#include <iostream>
using namespace std;
int main()
{
int g, count=0;
cout << "Enter the number" << endl;
cin >> g;
while (g > 0)
{
count = count +1;
g = g/10;
}
cout << count << endl;
system ("pause");
return 0;
}
你做过任何调试吗?
你认为g的什么值会使这个条件成立?
(g > 0 && g <= 10)
这应该足以让您找出问题所在。
如果 g> 10,则
(g > 0 && g<=10)
是错误的。
如果你真的想为此使用循环(log10-call 可以完成这项工作),请使用这样的东西(未经测试):
for (count=0;g>0;g/=10,count++) {}
这几乎与您写的相同,但没有g<10
条件。
此代码将重现位数。
#include <iostream>
using namespace std;
int main()
{
int g, count=0;
cout << "Enter the number" << endl;
cin >> g;
while (g > 0)
{
count = count +1;
g /= 10;
}
cout << count << endl;
return 0;
}
除此之外,还有另一种解决此问题的方法
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int g, count=0;
cout << "Enter the number" << endl;
cin >> g;
count = (int)(log10((double)g));
if (g == 0)
count = 0;
cout << count + 1 << endl;
return 0;
}
首先将字符串转换为 int 然后尝试查找其长度有点麻烦。你为什么不只看绳子?
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter the number" << std::endl;
std::string g;
std::cin >> g;
std::cout << g.size() << "n";
}
注意:这不会修剪前导零;我把这个留给你。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 循环在计数器中不起作用
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- 如何将计数器添加到气泡排序中以计数数字比较
- 对于 C++ 中的每个计数器循环不会以特定数字递增
- C++ 中的数字计数器
- 提取计数器注册某个数字的频率
- 为小循环计数器选择什么数字类型
- for循环需要运行LLONG_MAX次数,但是计数器变量也需要表示有符号的数字.你用什么类型的柜台?