简体   繁体   English

C程序如何反转一个数字需要解释

[英]C program for how to reverse a number explanation needed

While searching for a C program on how to reverse a string, i came across the below program.在搜索有关如何反转字符串的 C 程序时,我遇到了以下程序。 I am already familiar with a program where we take the length of the string and then minus each character and find the reverse.我已经熟悉一个程序,我们取字符串的长度,然后减去每个字符并找到相反的结果。 But this a different program.但这是一个不同的程序。 So can someone please tell me how this code works?那么有人可以告诉我这段代码是如何工作的吗? Help will be gratefully accepted.帮助将被感激地接受。 compiler used is Borland Turbo c.使用的编译器是 Borland Turbo c。

#include<stdio.h>
#include<conio.h>
#include<string.h>

void main() {
    char str[50];
    char rev[50];
    int i, j, n;
    clrscr();
    printf("enter the string to be reversed:");
    scanf("%s", &str);
    for (i = 0; str[i] != 0; i++) {
        n = i - 1;
    }
    for (j = 0; j <= i - 1; j++) {
        rev[j] = str[i];
        n--;
    }
    printf("the reverse of the string is:%s", rev);
    getch();
}

Your code doesn't work as it is supposed to.Have you tried it ?您的代码无法正常工作。您尝试过吗?

Consider this approach to reverse a string :考虑这种反转字符串的方法:

#include <stdio.h>
#include <string.h>

int reverse(char *Str);
void swap(char *x, char *y);

int main(int argc, char *argv[]) {
    char Str[255];
    printf("enter the string to be reversed : ");
    scanf("%s", Str);
    reverse(Str);
    printf("the reverse of the string is : %s\n", Str);
}

int reverse(char *Str) {
    size_t len = strlen(Str);
    size_t n = len / 2;
    char *begin = Str;
    char *end = (Str + len) - 1;

    while (n > 0) {
        swap(begin, end);
        begin++;
        end--;
        n--;
    }
    return 0;
}

void swap(char *x, char *y) {
    char tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;
}

In C, strings are NUL-terminated meaning that it has '\\0' at the end signifying the end of the string.在 C 中,字符串是以 NUL 结尾的,这意味着它的末尾有'\\0'表示字符串的结尾。 The code you've posted currently has two issues:您发布的代码目前有两个问题:

  1. This:这个:

     scanf("%s", &str);

    should be应该

    scanf("%s", str);

    as %s expects a char* , not a char(*)[50] .因为%s需要char* ,而不是char(*)[50]

  2. This:这个:

     rev[j] = str[i];

    should be应该

    rev[j] = str[n];
  3. rev should be NUL-terminated before printing. rev应该在打印前以 NUL 结尾。 Add添加

    rev[j] = '\\0';

    just before就在之前

    printf("the reverse of the string is:%s", rev);

    to avoid Undefined Behavior.避免未定义行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM