打印地址而不是预期值

时间:2015-04-06 07:34:36

标签: c

我正在尝试编写一个简单的程序。我是一个初学者,我没有得到总值。当我想要打印时。我得到一个地址作为输出。任何人都可以解释我的错误是什么,并纠正我的计划。

#include<stdio.h>
void main()
{
    int first,second,total;
    printf("enter the value for the first");
    scanf("%d",&first);
    printf("enter the value for the second");
    scanf("%d",&second);
    total=power(first,second);
    printf("The value for power is %d",power);
} 

int power(int doom1,int doom2)
{
    int temp=doom1;
    int i;
    for(i=1;i<=doom2;i++)
    {
            temp=temp*doom1;
    }
    return temp;
}

3 个答案:

答案 0 :(得分:3)

您正在打印错误的变量:

total=power(first,second); //here you are getting return value in variable total
printf("The value for power is %d",power);  // power is the function name not variable

将此行替换为:

printf("The value for power is %d",total);  // you need to print `total`  

此外,您必须在main()之前声明您的函数原型:

int power(int ,int);

您应该使用int main()

int main()
{
    // your code
    return 0;
}

答案 1 :(得分:1)

除了将total传递给printf而不是power之外,正如您刚刚开始一样,请指出始终为变量赋予初始值(初始化它们)。这可以防止尝试从未初始化的空间读取,这是新C程序员的祸根。 (它会为你节省很多麻烦)。尝试从未初始化的变量中读取未定义的行为。这可能会导致任何因未被注意而导致程序崩溃的情况。这是应该避免的。

另外,正如我在评论中解释的那样,在C中,函数main()是类型int并且它向其调用者(通常是shell或其他程序)返回一个值。使用不带参数的main时,正确的形式是:

int main (void)

接受参数时,正确的形式是:

int main (int argc, char **argv)

在任何一种情况下,它应在完成时返回值。最后只需return 0;即可。 exit (0);是您可以用来返回值的另一个函数。您还将看到main的形式,其参数写为:

int main (int argc, char *argv[])

第一种和第二种形式是彼此的实际等价物,第一种认识到传递给C中的函数的数组将衰减为指针。但就目前而言,只要明白它们就是等价的。

您的my_power计算中也有错误。 int temp = doom1;应该是int temp = 1;您的计算返回的值是实际产品的两倍。

您的语法风格取决于您,但我建议通过使用自由空格和行来扩展您的语法将使您的代码更具可读性并使查找错误更容易一些。以下是关于所有这些要点的示例:

#include <stdio.h>

int my_power (int doom1, int doom2);

int main (void)
{
    int first = 0;      /* Always initialize your variable to prevent */
    int second = 0;     /* an inadvertant read from an unitialized    */
    int total = 0;      /* value which is Undefined Behavior (bad).   */

    printf ("\n enter the value for the first : ");
    scanf ("%d",&first);

    printf (" enter the value for the second: ");
    scanf ("%d",&second);

    total = my_power (first,second);

    printf ("\n The value for my_power is: %d\n\n", total);

    return 0;
} 

int my_power (int doom1, int doom2)
{
    int temp = 1;
    int i = 0;

    for (i = 1; i <= doom2; i++)
        temp = doom1 * temp;

    return temp;
}

<强>输出

$ ./bin/simple_function

 enter the value for the first : 2
 enter the value for the second: 7

 The value for my_power is: 128

答案 2 :(得分:0)

您正在尝试打印没有参数的“power”

printf("The value for power is %d",power);

你应该做

printf("The value for power is %d",total);

printf("The value for power is %d",power(first,second));
相关问题