相关疑难解决方法(0)

类型转换 - unsigned to signed int/char

我试过执行以下程序:

#include <stdio.h>

int main() {
    signed char a = -5;
    unsigned char b = -5;
    int c = -5;
    unsigned int d = -5;

    if (a == b)
        printf("\r\n char is SAME!!!");
    else
        printf("\r\n char is DIFF!!!");

    if (c == d)
        printf("\r\n int is SAME!!!");
    else
        printf("\r\n int is DIFF!!!");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

对于这个程序,我得到输出:

char是DIFF !!! int是相同的!

为什么我们两者都有不同的输出?
输出应该如下?

char是相同的!int是相同的!

一个键盘连接.

c types type-conversion integer-promotion signedness

73
推荐指数
4
解决办法
3万
查看次数

strcmp()返回C中的值

我正在学习strcmp()C.我明白当两个字符串相等时,strcmp返回0.

但是,当strcmp第一个字符串小于第二个字符串时,手册页状态返回小于0时,它是指长度,ASCII值还是其他什么?

c strcmp

21
推荐指数
3
解决办法
7万
查看次数

比较两个字符串的最佳或最快方法是什么?

我不确定下面的代码有多快.如果有人知道比这更快/更优化的代码,请告诉我.

int xstrcmp(char *s1, char *s2)
{
  while (*s1 == *s2++)
            if (*s1++ == 0)
                    return (0);
  return (*(const unsigned char *)s1 - *(const unsigned char *)(s2-1));
}
Run Code Online (Sandbox Code Playgroud)

c++ string performance

5
推荐指数
3
解决办法
1万
查看次数

C - strcmp与if语句相关

在下面的代码中,我使用strcmp比较两个字符串,并将此比较作为if语句的条件.使用下面的代码,输出将是hello world,因为字符串"one"等于字符串"two".

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

char one[4] = "abc";
char two[4] = "abc";

int main() {

    if (strcmp(one, two) == 0) {
        printf("hello world\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想更改程序,hello world如果两个字符串不同则打印它,所以我改变程序:

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

char one[4] = "abc";
char two[4] = "xyz";

int main() {

    if (strcmp(one, two) == 1) {
        printf("hello world\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它不打印任何东西.

c string if-statement function strcmp

4
推荐指数
1
解决办法
6771
查看次数

可能执行不好的strcmp

我找到了strcmp函数的一个实现,我把它展示给了一个朋友,他说下面的"值得注意的是它并不总是返回两个不同字符之间的差异;它实际上允许返回任何整数,前提是符号是与字节之间的差异相同." 然后没有给我进一步解释,代码就是这个

int
strcmp(s1, s2)
    register const char *s1, *s2;
{
    while (*s1 == *s2++)
        if (*s1++ == 0)
            return (0);
    return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1));
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释什么是错误吗?什么样的字符串可以导致失败?

c strcmp

1
推荐指数
1
解决办法
196
查看次数