简体   繁体   English

从右手边开始循环的C编程

[英]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值。

Updated code: 更新的代码:

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: 好吧,我可能会在您的代码中注明一些注意事项,以免您将来遇到错误:

  • You're using sprintf() instead of snprintf() . 您使用的是sprintf()而不是snprintf() This is ( almost ) as dangerous as using the evil gets() . 几乎与使用邪恶的gets()一样危险。
  • You don't do bounds checking (see previous note). 您无需进行边界检查(请参阅前面的注释)。
  • You use fixed-size arrays for dynamically-sized input (see the two previous notes). 您将固定大小的数组用于动态大小的输入(请参阅前面的两个说明)。
  • 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.

相关问题 如何从屏幕右侧而不是 C 中通常的左侧按 output 进行打印? - How to print by output from the right hand side of the screen instead of the usual left hand side in C? “ &amp;&amp;”或“ ||”的右操作数 是可能有副作用的表达 - Right hand operand of '&&' or '||' is an expression with possible side effects 将首先评估表达式的右侧 - will right hand side of an expression always evaluated first C中的右手迷宫遍历 - Right hand maze traversal in C C编程,从重复的代码进行循环 - C programming, making a loop from code that is repetitive 逻辑运算符的右手操作数 || 由于调用 function(MISRA-C 2012Rule 13.5)而具有持续的副作用 - The right hand operand of a logical operator || has persistent side effects because of calling function (MISRA- C 2012Rule 13.5) 为什么不能通过使用$来识别Makefile中规则的右侧? - Why can't the right hand side of a rule in Makefile be recognized by using $? 在带有指针变量的表达式右侧使用逻辑非运算符(两次) - Use of logical not operator (twice) on right hand side of expression with pointer variable 包含赋值运算符右侧数据类型的方括号 - Brackets containing a datatype on right hand side of assignment operator C编程,这是一个无限循环吗? - C programming, Is this an infinite loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM