如何输出 int 乘数的浮点乘积?

发布于 2024-10-02 07:39:29 字数 1093 浏览 2 评论 0原文

我正在尝试计算一个数字的指数。当我以 int 方式执行所有操作时,我得到了正确的结果,但输出必须是浮点型,当我尝试在 printf() 中使用 %f 进行转换时,我得到 0,当我使用 %d 时,我得到正确的结果。我无法更改程序的 main() 部分,只能更改 *powerArgs() 函数。程序输入是 3、5。

完全公开,这是学校作业的一部分。我不要求完整的代码。我希望有一个更笼统的答案,告诉我我忘记了什么,可能我应该在哪些领域进行更多研究以自己找到答案。

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

int *powerArgs(int *pA, int *pB);

/* MAIN */
int main(int argc, char **argv)
{

    if (argc != 3)
    {
       printf("?Invalid number of arguments\n");
       system("pause");
       exit(1);
    }

    int parmA = atoi(argv[1]);
    int parmB = atoi(argv[2]);
    int idx;

/* Part C: Raise parmA to the power of parmB.  Return pointer to the result */    
/*         Reset the original values after we print the result */
    printf("%d raised to the %d power is %0.1f\n", parmA, parmB, *powerArgs(&parmA, &parmB));

    printf("\n");  

    system("pause");
    exit(0);
}

int *powerArgs(int *pA, int *pB)
{
      int idx, result = *pA;

      for (idx = 1; idx < *pB; idx++)
      {
          result *= *pA;
      }

      return &result;
}      

I am trying to calculate the exponent of a number. When I do everything as int I get the correct result, but the output must be float, when I try to convert with %f in printf() I get 0, when I use %d I get the correct result. I cannot change the main() portion of the program, I can only alter the *powerArgs() function. The program input is 3, 5.

Full disclosure, this is part of a school assignment. I am not asking for complete code. I would appreciate a more general answer showing me what I am forgetting, possibly what area I should study more to find the answer myself.

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

int *powerArgs(int *pA, int *pB);

/* MAIN */
int main(int argc, char **argv)
{

    if (argc != 3)
    {
       printf("?Invalid number of arguments\n");
       system("pause");
       exit(1);
    }

    int parmA = atoi(argv[1]);
    int parmB = atoi(argv[2]);
    int idx;

/* Part C: Raise parmA to the power of parmB.  Return pointer to the result */    
/*         Reset the original values after we print the result */
    printf("%d raised to the %d power is %0.1f\n", parmA, parmB, *powerArgs(&parmA, &parmB));

    printf("\n");  

    system("pause");
    exit(0);
}

int *powerArgs(int *pA, int *pB)
{
      int idx, result = *pA;

      for (idx = 1; idx < *pB; idx++)
      {
          result *= *pA;
      }

      return &result;
}      

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

青瓷清茶倾城歌 2024-10-09 07:39:29

floatint 在 C 中自动转换 - 您可以将其中一个分配给另一个,唯一需要注意的是,如果您将太大的浮点数分配给一个int,那么你会得到未定义的行为(或者可能是未指定的结果,我忘记了。无论哪种方式都不好)。

因此,您的 powerArgs 函数可以是:

float powerArgs(float a, int b) {
    // do some stuff and return a value
}

然后您可以将其调用为 powerArgs(parmA, parmB),即使 parmA 是一个 int。

编辑:如果您无法更改调用参数,则可以这样做

float powerArgs(int *a, int *b) {
    float base = *a;
    int exponent = *b;
    ...
}

如果您的教授确实将您的代码设置为调用函数的位置 *powerArgs(int *a, int *b),那么你的教授就是一个威胁。求幂函数没有理由返回一个指向浮点数的指针。您可以使用一个丑陋的解决方法:

float *powerArgs(int *a, int *b) {
    static float result;
    ...
    result = /* the result of the calculation */;
    return &result;
}

问题是,对 powerArgs 的所有调用共享同一个对象 resultstatic 阻止它在调用结束时停止存在,但从长远来看,共享会带来问题。这样做不是好的做法,但它可能是解决您所遇到的问题的最佳解决方案。

C++ 偷偷摸摸的解决方案:

struct FloatWrapper {
    float value;
    float operator*() {
        return value;
    }
    FloatWrapper(float f) : value(f) {}
};

FloatWrapper powerArgs(int *a, int *b) {
    ...
    float result = /* whatever */;
    ...
    return result;
}

这会按值返回 FloatWrapper 类的对象,并且 FloatWrapper 会重载 * 运算符。这意味着 *powerArgs(...) 计算结果为该函数首先应按值返回的浮点数,不需要指向任何特殊存储位置的指针。

顺便说一句,您可能想检查当 parmB 为 0 时您的函数会执行什么操作。

float and int convert automatically in C - you can assign either one to the other, and the only thing to watch out for is that if you assign too large a float to an int, then you get undefined behavior (or possibly an unspecified result, I forget. Either way it's not good).

So, your powerArgs function can just be:

float powerArgs(float a, int b) {
    // do some stuff and return a value
}

Then you can call it as powerArgs(parmA, parmB), even though parmA is an int.

Edit: if you can't change the call parameters, you can do this instead

float powerArgs(int *a, int *b) {
    float base = *a;
    int exponent = *b;
    ...
}

If your professor has really set you code where the function is called as *powerArgs(int *a, int *b), then your professor is a menace. There is no earthly reason why an exponentiation function should return a pointer to a float. There's an ugly workaround you could use:

float *powerArgs(int *a, int *b) {
    static float result;
    ...
    result = /* the result of the calculation */;
    return &result;
}

The problem with this is, all calls to powerArgs share the same object result. static stops it from ceasing to exist at the end of the call, but the sharing will introduce problems in the long run. It is not good practice to do this, but it might be the best solution to the problem you've been set.

C++ sneaky solution:

struct FloatWrapper {
    float value;
    float operator*() {
        return value;
    }
    FloatWrapper(float f) : value(f) {}
};

FloatWrapper powerArgs(int *a, int *b) {
    ...
    float result = /* whatever */;
    ...
    return result;
}

This returns an object of class FloatWrapper, by value, and FloatWrapper overloads the * operator. This means that *powerArgs(...) evaluates to the float that the function should have returned by value in the first place, without needing a pointer to any special storage place.

By the way, you might want to check what your function does when parmB is 0.

我只土不豪 2024-10-09 07:39:29

首先,您的 int *powerArgs(int *pA, int *pB) 函数返回局部变量的地址,这会导致未定义的行为。请使用以下代码:

int powerArgs(int *pA, int *pB)
{
  int idx, result = *pA;

  for (idx = 1; idx < *pB; idx++)
  {
      result *= *pA;
  }

  return result;
}

接下来,如果您想转换为 float,则不应在调用 printf() 时执行此操作,而应将值转换为 < code>float 调用之前,如下所示:

printf("%d raised to the %d power is %0.1f\n", parmA, parmB, (float)powerArgs(&parmA, &parmB));

First, your int *powerArgs(int *pA, int *pB) function returns the address of a local variable, which results in undefined behavior. Use the following instead:

int powerArgs(int *pA, int *pB)
{
  int idx, result = *pA;

  for (idx = 1; idx < *pB; idx++)
  {
      result *= *pA;
  }

  return result;
}

Next, if you want to convert to float, you shouldn't do that in the call to printf(), but rather convert the value to float before the call like so:

printf("%d raised to the %d power is %0.1f\n", parmA, parmB, (float)powerArgs(&parmA, &parmB));
戈亓 2024-10-09 07:39:29

当函数终止时,它的所有局部变量都不再存在(并且它们的地址指向垃圾)。为了取悦你的老师,他提出了那个非常尴尬的界面,你必须找到一种方法来让对象在函数存在后保持活动状态。

您至少有 3 个选择:
a) 重用输入参数之一
b) 使用全局变量
c) 使用静态变量

选项 a)

int *powerArgs(int *pA, int *pB) {
    /* calculate */
    *pA = CALCULATED_VALUE;
    return pA;
}

选项 b)

int global_power;

int *powerArgs(int *pA, int *pB) {
    /* calculate */
    global_power = CALCULATED_VALUE;
    return &global_power;
}

选项 c)

int *powerArgs(int *pA, int *pB) {
    static int static_power;
    /* calculate */
    static_power = CALCULATED_VALUE;
    return &static_power;
}

这些“解决方案”都不好;最不坏的是选项c)

When a function terminates, all its local variables cease to exist (and their addresses point to garbage). To please your teacher who came up with that very awkward interface, you have to find a way to keep an object alive after the function exists.

You have, at least, 3 options:
a) reuse one of the input parameters
b) use a global variable
c) use a static variable

option a)

int *powerArgs(int *pA, int *pB) {
    /* calculate */
    *pA = CALCULATED_VALUE;
    return pA;
}

option b)

int global_power;

int *powerArgs(int *pA, int *pB) {
    /* calculate */
    global_power = CALCULATED_VALUE;
    return &global_power;
}

option c)

int *powerArgs(int *pA, int *pB) {
    static int static_power;
    /* calculate */
    static_power = CALCULATED_VALUE;
    return &static_power;
}

Neither of these "solutions" is good; the least bad is option c)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文