簡體   English   中英

為什么我得到0而不是C中的x-y和x / y計算結果

[英]why do i get 0 instead the result of calculation x - y and x/y in C

在這段代碼中,我以為我會得到x / y和x-y的計算結果,但是程序對i和j顯示0。 怎么了?

#include <stdio.h>

float calculate(float, float);
float i, j;

int main()
{
    float a, b;

    printf("Enter two numbers:\n");
    scanf("%f%f", &a, &b);
    printf("\nThe results are: %f  %f  %f\n", calculate(a, b), i, j);

    return 0;
}

float calculate(float x, float y)
{
    float r;

    r = x * y;
    i = x / y;
    j = x - y;
    return r;
}

這是未定義的行為 ,當您在同一printf中調用calculate()函數,並且在該printf中計算i和j時(同一函數)。 順便說一句,使用全局變量(i,j)不是一個好主意...僅出於測試目的,您可以在i和j的下一個printf之前進行calculate()。

您可以使用以下方法測試該行為:

#include <stdio.h>

float calculate(float, float);
float i, j;
int main()
{
    float a, b;

    printf("Enter two numbers:\n");
    scanf("%f%f", &a, &b);
    printf("\nThe results are: %f", calculate(a, b));
    printf("    %f    %f\n", i, j);

    return 0;
}

float calculate(float x, float y)
{
    float r;

    r = x * y;
    i = x / y;
    j = x - y;
    return r;
}

它可能與printf函數中參數的解析,引用和執行順序有關。 printf函數使用參數從右到左方向。 您可以通過以下代碼輕松檢查訂單。

#include <stdio.h>

float calculate(float, float);
float i, j;

int main()
{
    float a, b;

    printf("Enter two numbers:\n");
    scanf("%f%f", &a, &b);
    //printf("\nThe results are: %f  %f  %f\n", calculate(a, b), i, j);
    printf("\nThe results are: %f  %f  %f\n", i, j, calculate(a, b));

    return 0;
}

float calculate(float x, float y)
{
    float r;

    r = x * y;
    i = x / y;
    j = x - y;
    return r;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM