gpt4 book ai didi

c - 我相信我对程序中的指针感到困惑

转载 作者:行者123 更新时间:2023-11-30 20:11:46 26 4
gpt4 key购买 nike

下面我创建了一个进入 while 循环的函数。在 while 循环中,调用 if 语句来遍历列表并检查数字以查看哪个数字最大,哪个数字最小。当我运行该程序时,仅调用一个 printf() ,并且多次打印相同的 printf() 。它似乎选择两个数字并在同一个 printf() 函数下打印它们。我知道 firstNumber = firstNumber->next; 应该遍历列表。 secondNumber = secondary->next->next; 不是应该指向列表中的下一个数字吗?

typedef struct A_NewNumber {
struct A_NewNumber *next;
double newNum;
} NewNumber;

void NumberSize(NewNumber *start) {

NewNumber *firstNumber = start;
NewNumber *secondNumber = start;

if(start != NULL) {
while (secondNumber != NULL && secondNumber->next != NULL) {
secondNumber = secondNumber->next->next;
firstNumber = firstNumber->next;
if(secondNumber > firstNumber) {
printf("The biggest number is:%lf \n",secondNumber->newNum);
} else {
printf("The smallest number is:%lf \n",firstNumber->newNum);
}
firstNumber = firstNumber->next;
}
}
}

完整程序的运行示例:

 Please enter a number or
'quit' to stop or 'print' to print/calculate
12
Please enter a number or
'quit' to stop or 'print' to print/calculate
13
Please enter a number or
'quit' to stop or 'print' to print/calculate
14
Please enter a number or
'quit' to stop or 'print' to print/calculate
15
Please enter a number or
'quit' to stop or 'print' to print/calculate
16
Please enter a number or
'quit' to stop or 'print' to print/calculate
17
Please enter a number or
'quit' to stop or 'print' to print/calculate
print
Numbers:12.000000
Numbers:13.000000
Numbers:14.000000
Numbers:15.000000
Numbers:16.000000
Numbers:17.000000

The biggest number is:14.000000
The biggest number is:16.000000
The smallest number is:17.000000

最佳答案

if() 内部的比较应该基于值,而不是指针。

if( num1 > num2) {
// Do something.
} else {
// Do something else.
}

这是因为您在 while() 循环内执行了两次 firstNumber = firstNumber->next; 语句。

firstNumber = firstNumber->next;
firstNumber = firstNumber->next;

这使得secondNumber == firstNumber;

关于c - 我相信我对程序中的指针感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39440396/

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