用vs编写程序时返回值被忽略,未初始化局部变量

用vs编写用户可录入尽寸的计算箱子的空间重量程序时出现返回值被忽略和未初始化局部变量的错误提示,该如何解决?

img

  • scanf 返回值 警告 可以忽略
  • volume 这个变量还未初始化,你右边 多写了一个吧,改成 length 吧

img

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7551478
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:变量的赋值与初始化 变量VS常量
  • 除此之外, 这篇博客: 【数据结构】——栈和队列的数组vs链表,含实操源码(中缀表达式,括号匹配,循环队列实现)中的 (2)栈判空 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
    bool StackEmpty(ST* ps)
    {
    	assert(ps);
    	//直接返回
    	return ps->top == 0;
    }
  • 以下回答来自chatgpt:

    问题分析:

    错误提示中第一个警告 C4189 是提示变量 weight 虽然被初始化了但从未被使用过,因此可以将其删除。第二个警告 C4715 则是因为在 calculateWeight 函数中,只有满足一定条件时才有返回值,因此需要在函数外部设置一个默认返回值。

    解决方案:

    1. 删除未使用的变量 weight,代码如下:
    int calculateWeight(int length, int width, int height) {
        if(length > 0 && width > 0 && height > 0) {
            return length * width * height * 5;
        }
        // 设置默认返回值
        return -1;
    }
    
    1. 在 calculateWeight 函数中添加默认返回值,可以将其设置为 -1,代码如下:
    int calculateWeight(int length, int width, int height) {
        int weight;
        if(length > 0 && width > 0 && height > 0) {
            weight = length * width * height * 5;
            return weight;
        }
        // 设置默认返回值
        return -1;
    }
    

    最终代码如下:

    #include <stdio.h>
    
    int calculateWeight(int length, int width, int height) {
        if(length > 0 && width > 0 && height > 0) {
            return length * width * height * 5;
        }
        // 设置默认返回值
        return -1;
    }
    
    int main() {
        int length, width, height;
        printf("请输入箱子的长度、宽度和高度:");
        scanf_s("%d %d %d", &length, &width, &height);
        int weight = calculateWeight(length, width, height);
        if(weight == -1) {
            printf("请输入有效尺寸!\n");
        } else {
            printf("该箱子的重量为%d千克。\n", weight);
        }
        return 0;
    }
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^