gpt4 book ai didi

c - 将比较运算符作为 char 与 scanf 并在 if 中使用

转载 作者:太空宇宙 更新时间:2023-11-04 03:34:04 24 4
gpt4 key购买 nike

#include<stdio.h>
int main()
{
int a,b;
char c;

printf("Enter value for a and b ");
scanf("%d %d ",a,b);
printf("Enter c(<) or c(>) for comparison");
scanf(" %c ",c);

if(a ? b)
{
printf("%d ",a);
}
}

我想从 scanf 中获取 char c 并将其放在 ? ,并且我想以这种方式运行 if 语句,是否可以以任何方式运行?

最佳答案

不可能像 C 那样在运行时动态更改比较运算符。

相反,您可以使用如下所示的方法(我还对代码添加了一些修复,在注释中进行了解释):

#include<stdio.h>
int main()
{
int a, b;
char c;

printf("Enter value for a and b ");
// No spaces neeeded after specifiers, otherwise the user have to input additional data
// Pointers to the variables have to be passed to scanf
scanf("%d%d", &a, &b);
printf("Enter c(<) or c(>) for comparison ");
// A single space needed before %c , to discard previous newline
scanf(" %c", &c);

int condition = 0; // initial: false
// For every of the operators, assign the comparison result to 'condition'
if (c == '<')
condition = (a < b);
else if (c == '>')
condition = (a > b);
else
printf("Unknown operator: %c\n", c);

// Test for condition
if (condition)
{
printf("%d\n",a);
}
// Add a return statement
return 0;
}

关于c - 将比较运算符作为 char 与 scanf 并在 if 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976763/

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