gpt4 book ai didi

c - 如何用指针变量存储变量

转载 作者:行者123 更新时间:2023-11-30 15:03:51 25 4
gpt4 key购买 nike

我正在阅读一本关于 C 的书,想知道是否有人可以帮助我解决我遇到的问题。我的函数必须允许用户输入 float ,然后该数字必须存储在指针参数指向的变量中。当我打印 main 中的值时,我不断得到零。该函数只允许返回 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;
}

最佳答案

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);
}
}

修复:

  • 不必要的临时变量
  • 打印 double 的格式错误
  • 不测试输入是否有效

关于c - 如何用指针变量存储变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40537548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com