首页 > 解决方案 > 如何在 C 编程中使用 pow 函数,尤其是在 Eclipse 中

问题描述

我正在尝试在 Eclipse 中执行以下程序

在此处输入图像描述

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>

int main()
{
    int a, base, power;

    printf("\nBase:");
    fflush(stdout);
    scanf("%d", &base);
    fflush(stdin);

    printf("\nExponent:");
    fflush(stdout);
    scanf("%d", &power);
    fflush(stdin);

    a = pow(base, power);

    printf("\nAnswer: %d", a);
    fflush(stdout);

    return 0;
    getch();
}

上述程序的输出应如下所示

基数:指数:答案:

但我得到不同的输出

在此处输入图像描述

Base: 2

Exponent: 2

Enter base value: 2

Enter exponent value: 2

The exponent value of 2 is 4
Answer: 0

如您所见,输出要求我输入两次基值和指数值,而它应该只输入一次。

如何禁用此功能?

标签: ceclipse

解决方案


您应该在代码中修复几件事:

  • 返回后删除getch();线。它不会被执行,你应该得到关于这一行的编译器警告。现在您也可以删除#include<conio.h>,因为您不需要它。
  • fflush()的标准输入或标准输出(如评论中所指出的)。

生成的代码运行良好并产生预期的输出。你可以在这里查看:https ://onlinegdb.com/S1LLp9GoU

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int
main ()
{
  int a, base, power;

  printf ("\nBase:");
  scanf ("%d", &base);

  printf ("\nExponent:");
  scanf ("%d", &power);

  a = pow (base, power);

  printf ("\nAnswer: %d", a);

  return 0;
}

推荐阅读