簡體   English   中英

我正在檢查在不使用指針的情況下使用 function 返回 n_value 的解決方案

[英]i'm checking for solution to return n_value with a function without using pointers

這是我的程序 此程序返回:1 - 如果 a == b 的符號類似於 +a == +b,則返回 a 和 b 的循環排列。


2 - 如果 a.= b 的符號類似於 -a 和 +b,則返回 a+b 和 a*b。


正如您在第二個條件中看到的那樣,我必須返回 2 個值,所以我使用指針來執行此操作,正如您在下面的代碼中看到的那樣。 `

    #include <stdio.h>
    #include <stdlib.h>
    
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    //prototyping
    void result_Condition(float *pointer_a,float *pointer_b);
    
    int main(int argc, char *argv[]) {
        float a=0,b=0;
        printf("Enter the value of a : ");
        scanf("%f",&a);
        printf("Enter the value of b : ");
        scanf("%f",&b);
        result_Condition(&a,&b);
        return 0;
    }
    
    void result_Condition(float *pointer_a,float *pointer_b) {
    if(((*pointer_a>0)&&(*pointer_b>0))||((*pointer_a<0)&&(*pointer_b<0))) {
    float tomp;
    tomp = *pointer_a;
    *pointer_a = *pointer_b;
    *pointer_b = tomp;
    printf("The value of a is : %.2f\n",*pointer_a);
    printf("The value of b is : %.2f\n",*pointer_b);
    }
    if((*pointer_a>0)&&(*pointer_b<0)||(*pointer_a<0)||(*pointer_b>0)) {
    *pointer_a = *pointer_a + *pointer_b;
    *pointer_b = *pointer_b * (*pointer_a-*pointer_b);
    printf("The sum of a + b is : %.2f\n",*pointer_a);
    printf("The prod of a * b is : %.2f\n",*pointer_b);
    }
    }

您可以使用結構執行此操作:

struct Result {
    float a;
    float b;
};

struct Result result_Condition(float a, float b) 
{
    // Do what you need to do then return the two values as a structure
    return (struct Result){ a, b };
 }

int main(int argc, char *argv[]) {
    float a=0,b=0;
    
    // Get your values and use them
    struct Result r = result_Condition(a, b);
    printf("The value of a is : %.2f\n", r.a);
    printf("The value of b is : %.2f\n", r.b);

    return 0;
}

暫無
暫無

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

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