c - 为什么我必须做 c-48?\a 和 %2.f 是什么意思?
问题描述
这个程序是一个简单的计算器。起初很抱歉我的英语不好,我想知道'\a'和'%2.f'的含义是什么我知道%f是双倍但为什么是'2'。在'f'前面?就在最后我们将'dgt'设置为'c-48' 我想知道为什么'-48' 我是一名信息专业的学生,而我刚开始,你有什么特别的建议吗?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main()
{
printf("Simple Calculator: \nValid inputs are +-*/=and digits 0,...,9\n");
printf("Your input: \n");
double r = 0.0;
double dgt = 0.0;
char lst_opt = '+';
const int nxt_dgt = 1;
const int nxt_opt = 2;
int nxt_npt = nxt_dgt;
while (1)
{
char c = _getch();
switch (c)
{
case '+':
case '-':
case '*':
case '/':
if (nxt_npt != nxt_opt)
{
printf("\a");
break;
}
printf("%c", c);
lst_opt = c;
nxt_npt = nxt_dgt;
break;
case '=':
if (nxt_npt != nxt_opt)
{
printf("\a");
break;
}
printf("\n=%.2f", r); //double, but why .2?
nxt_npt = nxt_opt;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (nxt_npt != nxt_dgt)
{
printf("\a");
break;
}
printf("%c", c);
dgt = c-48;
switch (lst_opt)
{
case '+': r += dgt; break;
case '-': r -= dgt; break;
case '*': r *= dgt; break;
case '/': r /= dgt; break;
}
nxt_npt = nxt_opt;
break;
}
}
_getch();
}
解决方案
- 是什么
\a
意思?
比如\n
,一个转义字符,意思是“换行符”,它也是一个转义字符,意思是“警告”,当“打印”时会发出哔声。您可以在此处找到信息(包括其他特殊转义字符)。
- 为什么是负 48?
在代码中,它试图从一个字符中获取一个整数。它没有做类似的事情if(c == '3') i = 3;
,而是使用字符 '0'~'9' 在ACSII 表中的排序方式。可以看到,'0'~'9' 是从 48 到 57 紧密排列的。也就是说,'0' - 48
产生的结果为 0,其他结果也是如此。
%2.f
您知道%f
用于打印float
变量,这很好,但是还有更多需要了解。您可以格式化如何打印变量。代表“2.
打印至少 2 个字符宽的浮点数,也不应打印任何小数位”。更多printf()
格式信息在这里。
推荐阅读
- css - Ionic 5 - ion-button type="submit" css bug
- java - 可嵌入关系
- c# - .Net Framework 4.6.2 项目能否生成 .Net Core DLL?
- jquery - 使用 Jquery 显示更多数据
- r - R studio中ggplot()上x轴上的大数据
- python - 我很难创建一个找到tor节点的程序
- node.js - 文件上传并以可能的角度显示?
- google-apps-script - 通过脚本从电子表格中删除空行
- amazon-web-services - 长时间调用 aws api 网关
- ios - Swift - 带有英雄动画的 PanGestureRecognizer