gpt4 book ai didi

c - 我对变量的赋值和 While 函数有疑问

转载 作者:行者123 更新时间:2023-11-30 16:19:01 25 4
gpt4 key购买 nike

这是我的第一篇文章,很高兴成为这个社区的一部分。我在这方面完全是初学者,从我找到的不同教程中学习,这是我的第一个“程序”。我来找你们,因为我的代码有两个问题,我的程序员 friend 无法回答我(事实上,她告诉我在这里问):

我确信这是一个简单的答案,但我只是不知道,而且我在互联网上找不到任何正确的答案(或者我看起来不正确)。

谢谢大家!

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

int main()
{
// insert code here...
int num1;
int num3;
char ans[3];

printf("Enter first number: ");
scanf("%i", &num1);
printf("Enter second number: ");
scanf("%i", &num3);
while(!(strcmp(ans,"Sum") | (!(strcmp(ans,"Sub"))) | (!(strcmp(ans,"Mul"))) | (!
(strcmp(ans,"Div"))) == 0));
printf("What kind of operation do you want to make? Type Sum, Sub, Mul or Div:
");
scanf("%s", ans);
int Sum = num1 + num3;
int Sub = num1 - num3;
int Mul = num1 * num3;
// int Div = num1 / num2;

if((strcmp(ans,"Sum") == 0))
{
printf("The sum of both numbers give %d\n", Sum);
}
// {printf("%d y %d\n", num1, num2);
//}
if((strcmp(ans,"Sub") == 0))
{
printf("The substraction of both numbers give %d\n", Sub);
}
if((strcmp(ans,"Mul") == 0))
{
printf("The multiplication of both numbers give %d\n", Mul);
}
if((strcmp(ans,"Div") == 0))
{
printf("The division of both numbers give %d\n", num1 / num3);
}
{ if (!(strcmp(ans,"Sum") | (!(strcmp(ans,"Sub"))) | (!(strcmp(ans,"Mul"))) |
(!(strcmp(ans,"Div"))) == 0))
{
printf("This command does not apply, please type the correct option\n");
}
//((strcmp(ans, "Sum")) | (strcmp(ans, "Sub")) | (strcmp(ans, "Mul")) |
(strcmp(ans, "Div")) != 0) {



}
}
  • 当我运行该程序时,它不会为“num2”分配除 0 之外的任何值。

  • 我真正想要“while”函数做的是告诉您输入了错误的字符并返回到主要问题,直到您输入正确为止。

P.S:现在我已经发送了我编写的所有代码。

最佳答案

while(!(
strcmp(ans,"Sum") | (!(
strcmp(ans,"Sub"))) | (!(
strcmp(ans,"Mul"))) | (!(
strcmp(ans,"Div"))) == 0));

这没有任何意义。首先,逻辑或写成||而不是|。其次,最后的 ; 意味着在这种情况下永远循环,因为输入在循环内永远不会改变。您不应该使用 ; ,而是使用 { ... } 并将其放在 printf 和 scanf 周围以在它们周围形成循环。

将其重写为:

do
{
printf("What kind of operation do you want to make? Type Sum, Sub, 'Mul' or Div: ");
scanf("%s", ans);
}while( strcmp(ans,"Sum") &&
strcmp(ans,"Sub") &&
strcmp(ans,"Mul") &&
strcmp(ans,"Div") );

strcmp 如果字符串不匹配,则返回非零,这意味着这个 C 可以用英语读作:
“当输入不是 Sum 并且输入不是 Sub 并且输入不是 Mul 并且输入不是 Div 时,请要求输入”。

关于c - 我对变量的赋值和 While 函数有疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55745905/

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