我是 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);
}
我的程序的输出:
最佳答案
您的 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/