【问题标题】:If statement executing regardless of the condition [duplicate]无论条件如何,如果语句都执行[重复]
【发布时间】:2021-11-24 09:06:30
【问题描述】:

我正在编写一个 C 程序,它要求用户提供各种输入,其中一个是“是”或“否”问题。如果输入 Y 或 y,则应该执行 If 语句。但是,无论您输入什么,它都会通过 If 语句。

double phonePrice;
double phoneTax;
double phoneTotal;
double phoneApplePrice;
double phoneSubtotal;
double temp;
int yearsAppleCare;
char userAnswer;

//prompting for price
printf("Enter the price of the phone> ");
scanf("%f", &phonePrice);
fflush(stdin);

//prompting for iphone
printf("Is the phone an iPhone (Y/N) ?> ");
scanf("%c", &userAnswer);
fflush(stdin);

//nested if statements asking for apple care amount
if(userAnswer=="Y"||"y")
{
    printf("Enter the number of years of AppleCare> ");
    scanf("%d", &yearsAppleCare);
    
    if(yearsAppleCare<=0)
    {
        printf("You must choose at least 1 year of AppleCare");
        return 0;
    }
}

对此的任何帮助将不胜感激。

【问题讨论】:

  • userAnswer=="Y"||"y" 应该是userAnswer=='Y' || userAnswer=='y'
  • 使用if(userAnswer=='Y'||userAnswer=='y')
  • 这很可能是我第一次看到这个问题(或其等效问题)要求使用 Python 以外的语言。奇怪的是,它实际上并没有更频繁地发生。
  • @KarlKnechtel 我已经看到并关闭了可能数十或一百个 C 和 C++ 问题,但我从未见过这样的 python 问题。可能是因为你在python问题上比较活跃

标签: c if-statement char scanf logical-or


【解决方案1】:

对于初学者来说这个电话

fflush(stdin);

具有未定义的行为。删除它。

而不是这个调用

scanf("%c", &userAnswer);

使用

scanf(" %c", &userAnswer);
      ^^^^

跳过输入缓冲区中的空格,例如换行符'\n'

同样对于双变量使用转换说明符%lf。例如

scanf("%lf", &phonePrice);

if 语句中的条件

if(userAnswer=="Y"||"y")

等价于

if( ( userAnswer=="Y" ) || ( "y" ) )

由于隐式转换为指向其第一个元素的指针的字符串文字“y”不等于空指针,因此条件始终评估为逻辑真。

你需要写

if( userAnswer == 'Y' || userAnswer == 'y' )

使用整数字符常量 'Y''y' 而不是字符串文字。

【讨论】:

  • 非常感谢!我正在上 C 的课程,我的老师告诉我使用 fflush 来摆脱空间输入,但这是一个更好的方法。我之前学习的语言非常简单,或者语句不需要那么多规范。再次感谢!
【解决方案2】:

错误在这里:

//nested if statements asking for apple care amount
if(userAnswer=="Y"||"y")
{

应该是:

//nested if statements asking for apple care amount
if(userAnswer == "Y" || userAnswer == "y")
{

等等!不!

应该是:

//nested if statements asking for apple care amount
if( strcmp(userAnswer, "Y") == 0 || strcmp(userAnswer, "y") == 0)
{

为什么?

== 是什么意思?

C 语言中,== 表示两个对象相等。在字符串的情况下,对象是char*,即指向char 的指针。这些将是相等的当且仅当内存地址相同。在这种情况下,情况并非如此。

为什么?因为一个字符串被编译到程序中并在程序启动时初始化,而另一个字符串由用户提供到临时内存中。它们将位于不同的地址,因此指针不会相同。

您可能想要的是比较两个指针指向的内存位置的内容

为此提供了strcmp 函数。如果字符串相同,则此函数返回零。您可能还想考虑stricmp

【讨论】:

  • 您仍在将char 与指针进行比较。
  • "Y""y" 是字符串。应该是'Y''y'
  • 你说的都对!
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
相关资源
最近更新 更多