Beginner in C Programming [已关闭]

7jmck4yq  于 2023-10-16  发布在  其他
关注(0)|答案(2)|浏览(105)

**已关闭。**此问题需要debugging details。它目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
12天前关闭
Improve this question
你能帮我修改一下我的代码吗,好像有个错误。

#include <stdio.h>

int main() {
    int apples = 0;
    int dozenofApples;
    int extraApples;
    int totalPrice;
    char response;
   

    printf("Input amount apples: ");
    scanf("%d", &apples);
   
    dozenofApples = apples / 12;
    extraApples = apples % 12;
   
    printf("You have %d dozen apples ", dozenofApples);

    if (extraApples <= 1) {
        printf("and %d extra apples", extraApples);
       
    } else {
        printf("and %d extra apples", extraApples);
       
    }
    if (dozenofApples >= 2) {
        printf(" and this will cost you 120 PHP per dozen.");
       
    } else {
        printf(" and this will cost you 150 PHP per dozen.");
    }
   
    printf("\nContinue to purchase? Yes/No\n");
    scanf("%s", &response);
   
    if (response == 'Yes') {
        printf("Purchase Complete! Come again!");
    } else if (response == 'No') {
        printf("Purchase cancelled.");
    } else {
        return 0;
    }
    }
       
        return 0;
}

我希望响应字符集的输入是或否,并使用if else语句,它输出的结果时,购买完成或没有。

oalqel3c

oalqel3c1#

你用单引号写一个char字面值,比如'a'char s是用于单个字符,而不是整个字符串(多个字母)。要使用字符串,你需要像"Hello, World!"这样的双引号。你的'Yes''No'不正确。但是你不能用相等运算符(==)比较字符串,你需要strcmp()
下面的示例演示如何在代码中比较两个字符串。请注意,我使用fgets()作为用户输入,而不是像您一样使用scanf()

#include <stdio.h>   // fgets(), fprintf(), printf(), stdin, stderr
#include <stdlib.h>  // EXIT_FAILURE (1), EXIT_SUCCESS (0)
#include <string.h>  // strcmp()

int main() {
    // enough storage for "Yes" with the terminating NUL ('\0')
    char response[4];

    if (fgets(response, sizeof response, stdin) == NULL) {
        fprintf(stderr, "Failed to read input from the console!");
        return EXIT_FAILURE;
    }

    if (strcmp("Yes", response) == 0) {
        printf("Purchase Complete! Come again!");
    }
    else if (strcmp("No", response) == 0) {
        printf("Purchase cancelled.");
    }
    else {
        fprintf(stderr, "Invalid user input!");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
k75qkfdt

k75qkfdt2#

你好像有一个多余的支架没用过。

if (response == 'Yes') {
    printf("Purchase Complete! Come again!");
  } else if (response == 'No') {
    printf("Purchase cancelled.");
  } else {
    return 0;
  }
  } <-- this
return 0

简单地删除它

if (response == 'Yes') {
    printf("Purchase Complete! Come again!");
  } else if (response == 'No') {
    printf("Purchase cancelled.");
  } else {
    return 0;
  }

  return 0;

它会工作,快乐编码!

相关问题