为什么这个C程序的输出为零?

时间:2022-08-03 17:32:09

Will someone please explain this code in details and why 0 is coming?

有人请详细解释这段代码以及为什么会出现0?

Source Code:

源代码:

#include<stdio.h>
void main(){
char *str="Hello";
char *ptr = str;
char least =127;
while (*ptr++)
    least = ((*ptr)<(least))?(*ptr):(least);
printf("%d", least);
}

Output:

输出:

0

2 个解决方案

#1


4  

It looks like you're trying to find the smallest ASCII value in a string.

看起来你正在尝试在字符串中找到最小的ASCII值。

The problem with your code is that the while() loop ignores the first byte of the string and looks at the '\0' end-of-string marker instead. What you want to do is exit the loop before you compare least with zero.

您的代码的问题是while()循环忽略字符串的第一个字节,而是查看'\ 0'字符串结束标记。你想要做的是在最小与零比较之前退出循环。

Try this instead:

试试这个:

while (*ptr) {
    least = ((*ptr)<(least))?(*ptr):(least);
    ptr++;
}

#2


1  

All of your problems are caused by obfuscation - trying to write a simple algorithm as complicated as possible (bad programming). This does not only cause the mentioned bug(s) but also reduces readability and performance.

你的所有问题都是由模糊处理引起的 - 试图编写一个尽可能复杂的简单算法(糟糕的编程)。这不仅会导致上述错误,还会降低可读性和性能。

Had you tried to write the simple algorithm as simple as possible (good programming), there would have been no problems and the code would also execute faster:

如果你试图编写简单的算法尽可能简单(良好的编程),那就没有问题,代码也会执行得更快:

#include <stdio.h>
#include <limits.h>

int main (void)
{
  const char* str="Hello";
  char least = CHAR_MAX;

  for(size_t i=0; str[i] != '\0'; i++)
  {
    if(str[i] < least)
    {
      least = str[i];
    }
  }

  printf("%c = %d", least, least);
}

#1


4  

It looks like you're trying to find the smallest ASCII value in a string.

看起来你正在尝试在字符串中找到最小的ASCII值。

The problem with your code is that the while() loop ignores the first byte of the string and looks at the '\0' end-of-string marker instead. What you want to do is exit the loop before you compare least with zero.

您的代码的问题是while()循环忽略字符串的第一个字节,而是查看'\ 0'字符串结束标记。你想要做的是在最小与零比较之前退出循环。

Try this instead:

试试这个:

while (*ptr) {
    least = ((*ptr)<(least))?(*ptr):(least);
    ptr++;
}

#2


1  

All of your problems are caused by obfuscation - trying to write a simple algorithm as complicated as possible (bad programming). This does not only cause the mentioned bug(s) but also reduces readability and performance.

你的所有问题都是由模糊处理引起的 - 试图编写一个尽可能复杂的简单算法(糟糕的编程)。这不仅会导致上述错误,还会降低可读性和性能。

Had you tried to write the simple algorithm as simple as possible (good programming), there would have been no problems and the code would also execute faster:

如果你试图编写简单的算法尽可能简单(良好的编程),那就没有问题,代码也会执行得更快:

#include <stdio.h>
#include <limits.h>

int main (void)
{
  const char* str="Hello";
  char least = CHAR_MAX;

  for(size_t i=0; str[i] != '\0'; i++)
  {
    if(str[i] < least)
    {
      least = str[i];
    }
  }

  printf("%c = %d", least, least);
}