【发布时间】:2015-07-18 14:57:06
【问题描述】:
我的程序编译没有错误,但是当我运行它时,在我输入半径这样的值后,它会因分段错误而退出。
我将它构造为采用可变数量的参数,但我怀疑这可能与我在“shape_area”函数运行期间调用每个参数的方式有关。
谁能帮忙解释一下我在这里做错了什么?
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
double shape_area(double shapetype, ...);
int main(void)
{
int shapetype;
double radius, side, length, width, area;
printf("\n\nPlease enter the type of shape you wish to get the area of:\n");
printf("| 1-Circle | 2-Square | 3-Rectangle |\n");
scanf("%d", &shapetype);
// Circle
if(shapetype == 1)
{
printf("\nPlease enter the radius of your circle: ");
scanf("%lf", &radius);
area = shape_area(shapetype, radius);
}
// Square
else if(shapetype == 2)
{
printf("\nPlease enter the side length of your square: ");
scanf("%lf", &side);
area = shape_area(shapetype, side);
}
// Rectangle
else if(shapetype == 3)
{
printf("\nPlease enter the side length of your square: ");
scanf("%lf", &length);
printf("\nPlease enter the side length of your square: ");
scanf("%lf", &width);
area = shape_area(shapetype, length, width);
}
else
{
printf("\n\nInvalid Input!\n");
return (0);
}
printf("\n\nArea of Shape: %lf\n\n", area);
return (0);
}
double shape_area(double shapetype, ...)
{
va_list args;
double temparea;
double radius;
double side;
double length;
double width;
radius = va_arg (args, double);
side = radius;
length = radius;
width = va_arg (args, double);
if(shapetype == 1)
{
temparea = M_PI*radius*radius;
}
if(shapetype == 2)
{
temparea = side*side;
}
if(shapetype == 3)
{
temparea = length*width;
}
va_end (args);
return temparea;
}
【问题讨论】:
-
为什么不使用
double shape_area(double shapetype, double radius, double width) -
你能提供样本输入吗?我第一次尝试运行它时以错误的答案正常退出,但没有段错误。
-
您是否尝试过使用调试器帮助您找到问题?它非常适合这些场景。
-
值得注意的是,此功能通常不能满足功能要求(正如我在回答中所说),但在练习中明确要求它。如果您(一个)不需要这样做,请不要这样做!
标签: c variables segmentation-fault arguments