2016-11-10 10 views
0

私はCで読んでいる本を読んでいて、誰かが私が持っている問題で私を助けてくれるのだろうかと思っていました。私の関数は、ユーザが浮動小数点数を入力できるようにしなければならず、その数はポインタパラメータによって指されている変数に格納されなければならない。私はメインの値を印刷するとき、私はゼロを得続けます。私は実際に値を返すことはできませんので、関数はtrueまたはfalseを返すことが許可されています。ここに私のコードです:ポインタ変数で変数を格納する方法

ちょうどガイダンスを探して、ありがとう!

#include <stdio.h> 
#include <stdbool.h> 
#pragma warning(disable: 4996) 




bool getDouble(double *pNumber); 


int main(void) 
{ 
    double d1 = 0; 
    double *pNumber; 
    bool i; 


    pNumber = &d1; 
    i = getDouble(pNumber); 
    printf("%f", *pNumber); 



} 


/* 
* Function: getDouble()Parameter: double *pNumber: pointer 
* to a variable that is filled in by the user input, if 
* valid 
* Return Value: bool: true if the user entered a valid 
* floating-point number, false otherwise 
* Description: This function gets a floating-point number 
* from the user. If the user enters a valid floating-point 
* number, the value is put into the variable pointed to by 
* the parameter and true is returned. If the user-entered 
* value is not valid, false is returned. 
*/ 
bool getDouble(double *pNumber) 
{ 

    /* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */ 
    char record[121] = { 0 }; /* record stores the string */ 
    double number = 0.0; 
    /* NOTE to student: indent and brace this function consistent with your others */ 
    /* use fgets() to get a string from the keyboard */ 
    fgets(record, 121, stdin); 
    /* extract the number from the string; sscanf() returns a number 
    * corresponding with the number of items it found in the string */ 
    if (sscanf_s(record, "%lf", &number) != 1) 
    { 
     /* if the user did not enter a number recognizable by 
     * the system, return false */ 
     return false; 
    } 
    pNumber = &number; /* this is where i think i am messing up */ 
    return true; 
} 

答えて

1

pNumber = &number;ちょうどあなたが何をしたいのか、あなたの関数のパラメータで、ローカル変数のアドレス(また、ローカル変数である)

が格納されます*pNumber = number;

ところで、あなたが直接することができますやる:if (sscanf_s(record, "%lf", pNumber) != 1)

そして、あなたのmainが大幅に簡素化し、より安全に行うことができます。

int main(void) 
{ 
    double d1; 

    pNumber = &d1; 
    if (getDouble(&d1)) 
    { 
     printf("%lf", d1); 
    } 
} 

修正:

  • 不要な一時変数入力が有効
であるかどうかを確認するために、二重
  • なしテストを印刷する
  • 間違ったフォーマット
  • 関連する問題