[英]C programming for loop start from right hand side
I was having some problem when trying to loop thru a string starting from right hand side based on the digit position entered by user. 尝试根据用户输入的数字位置从右手边开始循环通过字符串时遇到问题。 So basically this will be the output of my program:
所以基本上这将是我程序的输出:
Enter a number: 1234567
Enter the digit position: 3
digitValue1(): 5
And here is my code: 这是我的代码:
int main()
{
int num, digit, result;
printf("Enter the number: ");
scanf("%d", &num);
printf("Enter the digit position: ");
scanf("%d", &digit);
printf("digitValue1(): %d\n", digitValue1(num, digit));
return 0;
}
int digitValue1(int num, int k)
{
int result, i;
char str[15];
sprintf(str, "%d", num);
int len = strlen(str);
for (i = 0; i < len; i++) {
printf("%d ", i);
if (i == k) {
result = k;
}
}
return result;
}
So from what I did in the digitValue1()
is I take the int num entered by user and converted it into string and loop thru. 因此,根据我在
digitValue1()
所做的操作,我将用户输入的int num转换为字符串并循环通过。 However, it started from left hand side. 但是,它是从左侧开始的。 So this is my output:
这是我的输出:
Enter a number: 1234567
Enter the digit position: 3
digitValue1(): 3
I was thinking how should I make the loop start from right hand side. 我在想如何使循环从右侧开始。 I tried to reverse the for loop and it doesn't make sense.
我试图反转for循环,这没有任何意义。
Thanks in advance. 提前致谢。
Initialize i
to start at the end. 初始化
i
从结尾开始。 Remember that strlen()
is a Natural number, so the index of the last character is 1 less. 请记住,
strlen()
是自然数,因此最后一个字符的索引要少1。
There are a few other details to note: 还有其他一些注意事项:
This does not actually reverse the string being scanned; 这实际上并不会反转正在扫描的字符串。 rather it starts scanning from the end (right-side) of the string.
而是从字符串的末尾(右侧)开始扫描。
Since the loop is starting at the end of the string and working towards the front, the stopping condition needs to adjust to look for the k
th-last character. 由于循环是从字符串的末尾开始并朝着字符串的前端开始,因此需要调整停止条件以查找第
k
个最后一个字符。
We want the integer value of the result digit to be returned, so we must convert the char
to an int
. 我们希望返回结果数字的整数值,因此必须将
char
转换为int
。 That's easiest done by subtracting the ascii value for '0' from the result digit. 最简单的方法是从结果数字中减去0的ascii值。
int digitValue1(int num, int k)
{
int result, i;
char str[15];
sprintf(str, "%d", num);
int len = strlen(str);
for (i = len-1; i >= 0; i--) { // Loop backwards from end of str
printf("%d ", i);
if (len-i == k) { // Check if we are k from end
result = str[i] - '0'; // Convert digit char to int
}
}
return result;
}
This remains an exhaustive search... it will continue through the whole string even after finding the k
th-last element. 这仍然是一个详尽的搜索...即使找到了第
k
个最后一个元素,它也将贯穿整个字符串。 (Just as your original question did.) You'll want to think about how to optimize that, so it stops looking once the result is identified. (就像您最初提出的问题一样。)您将要考虑如何优化它,因此一旦确定了结果,它就会停止寻找。
Instead of a loop though, it would be more effective to calculate the index you're looking for: 虽然比起循环,但计算要查找的索引会更有效:
result = str[strlen(str)-k] - '0';
Well, I may note a few things in your code to let you avoid future bugs: 好吧,我可能会在您的代码中注明一些注意事项,以免您将来遇到错误:
sprintf()
instead of snprintf()
. sprintf()
而不是snprintf()
。 This is ( almost ) as dangerous as using the evil gets()
. gets()
一样危险。 strlen()
returns a size_t
, not an int
(this can cause really serious issues)! strlen()
返回一个size_t
, 而不是一个int
(这可能会引起严重的问题)! And finally, you appear to not understand the for
loop. 最后,您似乎不了解
for
循环。 Just remember this: in C(-like) languages, a for
loop is not exactly an iterator over a pseudo-list. 请记住这一点:在C(-like)语言中,
for
循环并不完全是伪列表上的迭代器。 In these languages, this: 在这些语言中,这是:
for(initializer; condition; helper) {
...
}
Is completely equivalent and shorthand for : 完全等同于 :
{
initializer;
while(condition) {
...
helper;
}
}
Thus, taking all this stuff into account, digitValue1()
could be reworded as something like this (note that the first position
is zero): 因此,考虑到所有这些东西,可以将
digitValue1()
改写成这样的东西(请注意,第一个position
为零):
int digitValue1(int num, int position) {
do {
int digit = num % 10;
num /= 10;
if(position-- == 0)
return digit;
} while(num != 0);
// This shall be understood as an error
return -1;
}
Hope this helps! 希望这可以帮助! Cheers, KemyLand.
干杯,凯米·兰德。
You can change your for loop from your side as well like following 您可以从侧面更改for循环,也可以像下面这样
for (i = len-1; i >= 0; i--)
{
// your implementation code
}
As you are starting from 0 position. 从0位置开始。 If you want to print from right then start from right.
如果要从右开始打印,请从右开始。 For that we need to set initialize value as len and ending with 0.
为此,我们需要将初始化值设置为len并以0结尾。
for (i = len-1; i >= 0; i--)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.