【问题标题】:Code is not working, and is not doing directed task [duplicate]代码不起作用,并且没有执行定向任务[重复]
【发布时间】:2020-12-28 10:17:51
【问题描述】:

代码是不言自明的,但我需要帮助,因为当我使用它时,它会跳过所有“If”情况并直接跳转到下一个循环。 “scanf”工作正常;变量“order”也正确接收输入。如果您知道如何解决它,请告诉我!祝你有美好的一天!

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

int main(){
    int side [3]; // Fries(0), Fried Squid(1), Cheese Fries(2)
    int combo [3]; // Spicy Chicken(0), Whopper(1), Double Whopper(2)
    int drinks[3]; // Cola(0), Vanilla Shake(1), Lemonade(2)
    int amount;
    char order [20];
    int total = 0;

    for(int i = 0; i < 3; ++i){
        combo[i] = 20;
        total = total + 20;
    }
     for(int i = 0; i < 3; ++i){
        side[i] = 20;
        total = total + 20;
    }
    for(int i = 0; i < 3; ++i){
        drinks[i] = 20;
        total = total + 20;
    }

    while (total > 0){
        printf("Make your order here: \n");
        scanf("%s %d", order, &amount);
        printf("%s\n", order);
        if(order == "Fries"){
            printf("A\n");A
            if(side[0] < amount){
                printf("Your order is invalid, and you are stinky.\n");
            }
            else{
                printf("B\n");
                printf("your order is here: %s x %d", order, amount);
                total = total - amount;
            }
            printf("C\n");
        }
        printf("D\n");
    }
    return 0;
}



【问题讨论】:

  • 我删除了其余的 IF 语句以简化代码!祝你好运!
  • 你需要使用类似strcmp的东西来比较字符串。 == 是比较指针,而不是数据。
  • @RetiredNinja TYSM!有效!对你的祝福! :D

标签: c if-statement comparison c-strings string-literals


【解决方案1】:

这样的if语句中的条件

if(order == "Fries"){

没有意义。比较了两个指针,很明显它们具有不同的值。即字符数组order 被隐式转换为指向其第一个元素的指针,字符串字面量也以相同的方式隐式转换为指针。

如果你甚至会写例子,请注意这一点

if("Fries" == "Fries"){

那么表达式的计算结果不必为逻辑真。表达式的结果取决于编译器选项,即编译器是将相同的字符串文字存储为一个字符串文字还是不同的字符串文字。

你需要的是比较两个字符串

#include <string.h>

// ...

if( strcmp( order, "Fries" ) == 0 ){

【讨论】:

    【解决方案2】:

    我现在无法测试,但我认为您应该使用strcmp 或strncmp 来比较字符串; == 运算符将只比较指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 2013-02-23
      相关资源
      最近更新 更多