【问题标题】:calculate a number raised to a power from user input, using scanf,使用scanf计算用户输入的幂次幂,
【发布时间】: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


【解决方案1】:

power 中没有什么可以阻止递归:

int power( int base, int exponent){   
    int total=1;
    int temp = power(base, exponent/2); // round and round we go

解决办法是放

if (exponent == 0)
     return total;  // base case;

在函数的顶部。 C++ 运行时库经常在这样的堆栈溢出时发出误导性的终止消息。

我也很想使用else,而不是明确地测试奇怪的情况。并修复一些缺少{} 的明显问题。

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2012-01-31
    • 2014-02-21
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多