简体   繁体   English

为什么我在输出后得到一些随机值?

[英]Why am I getting some random values after the output?

#include <stdio.h>
int main()
{
    int k;
    scanf("%d",&k);
    for(int i=0;i<k;i++)
    {
        char num[10];
        scanf("%s",&num);
        int x = num[0]-'0';
        int sum;
        int y;
        for(int i=0;i<10;i++)
        {
            if(num[i]=='\0')
            {
                y = num[i-1]-'0';
                sum = x+y;
                printf("%d\n",sum);
            }
        }   
    }
    return 0;
}

This program is to obtain the sum of first and last digit of a given number.该程序是获取给定数字的第一位和最后一位的总和。 I am getting some random values after the output.输出后我得到了一些随机值。 Can anyone please explain me this and how do I eliminate it?谁能解释一下这个以及如何消除它? enter image description here在此处输入图像描述

You have an inner loop that looks for the terminating null byte in the array.您有一个内部循环,用于查找数组中的终止空字节。 You find it, but then you keep looping through the array looking for more null bytes.你找到了它,但随后你继续遍历数组以寻找更多的空字节。 If you happen to find one, it takes whatever the prior byte is and treats it as the last digit.如果你碰巧找到一个,它会接受前面的字节并将其视为最后一位。

You can fix this by breaking out of the loop when you find the null terminator:您可以通过在找到空终止符时跳出循环来解决此问题:

    for(int i=0;i<10;i++)
    {
        if(num[i]=='\0')
        {
            y = num[i-1]-'0';
            sum = x+y;
            printf("%d\n",sum);
            break;
        }
    }   

Or by simply using strlen to find the end of the string.或者简单地使用strlen来查找字符串的末尾。

    y = num[strlen(num)-1]-'0';
    sum = x+y;
    printf("%d\n",sum);

The code also doesn't handle reading too many characters, which can overflow the buffer, or reading an empty string, in which case num[strlen(num)-1] is off the start of the array.该代码也不处理读取太多字符,这可能会溢出缓冲区,或者读取空字符串,在这种情况下num[strlen(num)-1]不在数组的开头。 You can address the former by putting a field width in the scanf format, and the latter with an explicit check:您可以通过在scanf格式中放置一个字段宽度来解决前者问题,而后者则通过显式检查来解决:

    char num[10];
    scanf("%9s",num);
    int sum;
    if (num[0] == 0) {
        sum = 0;
    } else {
        int x = num[0]-'0';
        int y = num[strlen(num)-1]-'0';
        sum = x + y;
    }
    printf("%d\n",sum);

The problem is that you don't stop the inner loop once you print the sum.问题是一旦打印总和,您就不会停止内部循环。 You continue and use the indeterminate elements in the array num beyond the string terminator.您继续使用数组num中超出字符串终止符的不确定元素。 That leads to undefined behavior .这会导致未定义的行为

You could solve it either by not having the inner loop (by using index 0 and strlen(num) - 1 ), or by using break to break out of the loop once you printed the sum.您可以通过不使用内部循环(通过使用索引0strlen(num) - 1 ),或者在打印总和后使用break跳出循环来解决它。

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

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