问题描述
假设,343是一个数字,我们需要找到它的长度,我们该怎么做,我们如何在c ++程序中打印,它是3?
Suppose, 343 is a number, and we are required to find its length, what do we do, how do we print in a c++ program, that it is 3?
<pre>// Main function of the C++ program.
#include <iostream>
using namespace std;
int main()
{
cout<<"Enter number to get the length of the number.";
cin>>x;
int xlen=0;
for(int i!=0; i=x/10; xlen++)
{ cout<<"The length is:"<xlen;
int l=xlen;
cout<<l;
}
return 0;
}
我的尝试:
请告诉我错误是什么以及解决方案。由于我是初学者,请帮我一个代码。谢谢。
What I have tried:
Kindly, tell me what the error is and the solution. As I am a beginner, please help me with a code. Thanks.
推荐答案
int x = 0;
cout << "Enter number to get the length of: ";
cin >> x;
现在你定义了长度,但是我把它设置为1,而不是零:
Now you defined the length, but I'd set it to one, not zero:
int xLen = 1;
为什么一个?因为0是一个数字,所以如果用户输入零,你应该说他的数字是一位数。
然后我会使用而
循环而不是
:
Why one? Because "0" is a digit, so if the user enters zero, you should say his number is one digit long.
Then I'd use a while
loop instead of a for
:
while (x != 0)
{
...
}
为什么同时
?只是因为它更容易阅读!
在循环中,我将更改 x
的值并计算每个数字:
Why a while
? Just because it's easier to read!
And inside the loop, I'd change the value of x
and count each digit:
x = x / 10;
xLen++;
然后在循环之后,打印你计算出的长度:
Then after the loop, print the length you worked out:
cout << endl << "The length is:" << xlen << endl;
for (initial expression; comparison expression; repeat expression)
{
// body
}
所以在你的情况下它应该是这样的:
So in your case it should be something like:
// Start by setting i to the input number
// repeat while i is not equal to zero
// at the end of each loop add 1 to xlen
for(int i = x; i != 0; xlen++)
{
i/=10; // divide i by 10
}
// print results here
这篇关于如何在C ++中找到问题的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!