【发布时间】:2017-12-01 13:18:50
【问题描述】:
所以我尝试使用 scanf 计算从用户输入提高到幂的数字,但我不断收到分段错误。有人知道为什么吗?这是我的代码:
int power( int base, int exponent){
int total=1;
int temp = power(base, exponent/2);
if (exponent == 0)
return total; // base case;
if (exponent % 2 == 0)// if even
total= temp * temp;
return total;
if(exponent %2 !=0)// if odd
total =(base * temp * temp);
return total;
}
void get_info(){
int base, exponent;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &exponent);
//call the power function
printf("%d",power(base,exponent));
}
int main(){
//call get_info
get_info();
return 0;
}
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
Visual Studio 有这个小块要分享:“警告 C4717:'power':在所有控制路径上递归,函数将导致运行时 堆栈溢出”(强调我的)。这是在我took the seat belts off 和
_CRT_SECURE_NO_WARNINGS之后。 -
@wally:我也关闭了屋顶,禁用了检查的迭代器。
-
并提防那些如果。您正在编写 C,而不是 Python:您需要在两个语句周围加上大括号。
-
@Bathsheba 当然,我们想要速度对吧?
标签: c++ segmentation-fault scanf