gpt4 book ai didi

c - While 循环带我去兜风(C 语言)!

转载 作者:行者123 更新时间:2023-11-30 21:36:24 25 4
gpt4 key购买 nike

我正在通过哈佛的 CS50 类(class)学习计算机科学。我正在学习如何定义新函数并将两个函数链接在一起。我随机创建了下面的脚本。我的 new_function 无法向主函数传递错误值,因此我的“while”循环就像狂野的西部一样打印。我在这里缺少什么明显的东西吗?谢谢!

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

bool new_function(int x1);

int main(void)
{
int whatever = get_int("get_int now!\n");

while(new_function(whatever) == true)
{
printf("still working\n");
}
}

bool new_function(int x1)
{
for(int i = 1; i <= x1; i++)
{
if(i != 5)
return true;
else if (i == 5)
return false;
}
return false;
}

最佳答案

要使 while 循环继续,条件必须为 true。深入挖掘我们发现
new_function(whatever) == true 条件。所以结果本质上取决于
new_function(int) 你在上面写的。

new_function(int) 作为参数接收的值是一个整数。
对于这种类型,对于 4 字节 int,其域是从负 2^3 到正 (2^^ - 1) 值的整数。

接下来,在 for 循环开始之前,它会创建一个初始化为 1 的新变量 i,然后检查 i 是否小于或等于 x1.如果为 true,则继续,否则结束 for 循环并返回 false。因此,从这些步骤中,我们看到,对于低于 1 的 x1 值,new_function(int x1) 返回 false,否则将进入循环。

进一步进入 for 循环,其中 i 的情况是从 1 到 x1,假设 x1 等于或大于 1 ,有一个条件检查if (i != 5),因为i总是初始化为1,所以与5不同,它总是执行return true,而else部分未到达。

所以继续,只要你给出一个大于 0 的数字,你的代码就会像狂野西部一样打印。 :)

关于c - While 循环带我去兜风(C 语言)!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53798091/

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