c - 如何调试产生意外输出的 C 程序?

标签 c

我是 C 编程新手,我不知道为什么我的程序没有打印所需的输出。

#include <stdio.h>
void main(void)
{
  char res,res1;
 float money=10;

 printf("***Wealcome to Peace of Mind***");
 printf("\nHello we have the menu please check::");
 printf("\n***Menú***");
 printf("\n");
 printf("\n<<<Bebidas>>>");
 printf("\n 1 - Coca-Cola = 1,5     2 - IceTea = 1,4");
 printf("\n 3 - Super Bock = 1,70    4 - Sumol = 1,6");
 printf("\n");
 scanf("%d",&res);
 switch(res)
 {
    case 1 || 'Coca-Cola':money - CocaCola;break;

 }
 printf("%.1f",money);

 //Is that result i want: 
    printf("\n%.1f",10-1.5);
}

我的程序的输出:

Screen Shot

最佳答案

您的 case 语句的语法不正确。该代码还使用 scanf() 读取整数,但将整数大小的值存储在 char 中。

我整理了代码:

#include <stdio.h>

int main(void)
{
    int  res;
    float cost  = 0;
    float money = 10;

    printf("***Wealcome to Peace of Mind***\n");
    printf("Hello we have the menu please check::\n");
    printf("***Menú***\n");
    printf("\n");
    printf("<<<Bebidas>>>\n");
    printf(" 1 - Coca-Cola  = 1,5     2 - IceTea = 1,4\n");
    printf(" 3 - Super Bock = 1,70    4 - Sumol  = 1,6\n");
    printf("\n");

    scanf("%d", &res);

    switch(res)
    {
        case 1:
           cost = 1.5;
           break;
        case 2:
           cost = 1.4;
           break;
        // TODO: case 3 & 4
        default:
           printf("Invalid Entry\n");
           cost = 0;
    }

    printf("money = %.1f\n", money - cost);

    return 0;
}

一些进一步的说明:

  • 正如评论者所指出的,将 \n 放在字符串的末尾
  • 编译时,打开警告,并尝试修复所有警告。
  • case block 中,最好使用 default 来捕获错误
  • 将饮料价格存储为#define常量(或作为值数组或某个公共(public)区域)是值得的,因此该值仅在程序中设置一次,其他一切都只是引用那个。)
    • #define COLA_COST 1.5

关于c - 如何调试产生意外输出的 C 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53383823/

相关文章:

c# - 简单 union 转换示例 - C 到 C#

c - Windows触发了一个断点——C语言

c - 如果没有循环,我如何在这里计算 'hits' ?

c - 预测输出

c - 使用 C 编写可用窗口

java - 如何查找两个数字是否是格雷码序列中的连续数字

c - 如何停止守护进程

c - 在 Cython 中通过双指针从 C 函数传递数据

c - Operation not Permitted on ALSA get hw parameters 函数

c - c中的管道问题