gpt4 book ai didi

c - 陷入 void 函数,if 条件

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

我是 C 新手。我坚持使用这段代码。关于代码和我的代码的问题如下。

问题:编写一个c程序输入一个数字(整数),如果输入的数字是奇数: print "(number) is an odd number",
如果输入的数字是偶数,
如果插入的数字是 20 或 10 到 20 之间,则乘以 2
如果插入的数字是 40 或 30 到 40 之间,则乘以 3
如果插入的数字是 50 或 40 到 50 之间,则乘以 4
最后显示相乘的答案。

我的代码

#include <stdio.h>
#include <stdlib.h>

void todo1 ();

int main() {
int i;
printf("Enter Number:\t",i);
scanf("%d",&i);
if (i%2!=0) {
printf("%d is an odd number",i);
}
else {
todo1();
}
return 0;
}


void todo1() {
if (i>40 || i<=50) {
i=i*4;
printf("%d", i);
} else if (i>30 || i<=40) {
i=i*3;
printf("%d", i);
} else if (i>10 || i<=20) {
i=i*2;
printf("%d", i);
}
}

最佳答案

以下是我给您的一些提示:

#include <stdio.h>
#include <stdlib.h>

int main(){
int i;
printf("Enter Number:"); // What were /t and i doing here?
scanf("%d",&i);
if (i%2) // "!=0" Can be replace by nothing
printf("%d is an odd number",i); //If you got only one line after a statement, you don't need braces
else{ // Your function isn't needed since its only called once
if (i>10 || i<=20)
i *= 2; // Same as i = i * 2
if (i>30 || i<=40)// You don't need an else since i doesn't change its value
i *= 3;
if (i>40 || i<=50)
i *= 4;
printf("%d", i);
}
return 0;
}

如果你仍然想使用一个函数,那么向它添加一个参数,它无法从主函数访问i变量:

void todo1(int i);

调用:

todo1(i);

关于c - 陷入 void 函数,if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40083069/

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