用vs编写用户可录入尽寸的计算箱子的空间重量程序时出现返回值被忽略和未初始化局部变量的错误提示,该如何解决?
bool StackEmpty(ST* ps)
{
assert(ps);
//直接返回
return ps->top == 0;
}
问题分析:
错误提示中第一个警告 C4189 是提示变量 weight 虽然被初始化了但从未被使用过,因此可以将其删除。第二个警告 C4715 则是因为在 calculateWeight 函数中,只有满足一定条件时才有返回值,因此需要在函数外部设置一个默认返回值。
解决方案:
int calculateWeight(int length, int width, int height) {
if(length > 0 && width > 0 && height > 0) {
return length * width * height * 5;
}
// 设置默认返回值
return -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;
}