【发布时间】:2019-09-08 18:48:43
【问题描述】:
这是我的第一篇文章,很高兴成为这个社区的一员。我是这方面的初学者,从我发现的不同教程中学习,这是我的第一个“程序”。我来找你们,因为我的代码有两个问题我的程序员朋友无法回答我(事实上,她告诉我在这里问):
我确信这是一个简单的答案,但我只是不知道,我在互联网上找不到任何正确的答案(或者我看起来不正确)。
谢谢大家!
#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:现在我已经发送了我写的所有代码。
【问题讨论】:
-
您的代码格式已损坏。为什么到处都是反引号?
-
你应该先从基本的开始。你的缩进不好,连代码都不完整。
-
strcmp(ans,"Sum")您的数组ans未初始化,它太短而无法容纳您要与之比较的字符串。Sum需要 4 个字符来存储字母和终止 nul 字符。 -
您的
while循环仅包含一条空指令。即使您为ans提供值,它也不会做任何事情 -
一般建议:您应该始终检查
scanf函数调用的结果。返回值是有含义的(您可以在手册页中找到它,这是任何教程的 C 标准)并且不应被忽略。您还应该始终在编译器中启用警告并仔细阅读。
标签: c variables while-loop