首页 > 解决方案 > 为什么我必须做 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();
}

标签: cvisual-studioperformancevariablescalculator

解决方案


  • 是什么\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()格式信息在这里


推荐阅读