c - 两个数相加

标签 c

我需要帮助来解决一个非常简单的问题。我编写了将两个数字相加的代码,但仅限于 float 类型。所以当我写 2+2 时,它给了我 4.0。我需要做什么才能只获得 4?但同时如果我写 5.2+5.3 得到 10.5

这是作业,不应包含 if 语句。

我尝试了所有变量类型,但它只给我不切实际的数字。如果有人提供帮助,我将不胜感激。

代码

#include <stdio.h>

/*Addition of two numbers*/

 int main()
{
    float a;
    float b;
    float x;

   printf("Enter the first number:\n");
   scanf("%f", &a);

   printf("Enter the second number:\n");
   scanf("%f", &b);

   x = a + b;

   /*Printing decimal number*/

   printf("Result: %.1f + %.1f = %.1f", a, b, x);

   return 0;

}

最佳答案

我想你要做的是对 printf 指令使用 g 格式说明符。这用于打印最短的表示。您可以在此处阅读有关格式说明符的更多信息:http://www.cplusplus.com/reference/cstdio/printf/

此代码打印您描述的方式:5 + 5 = 105.1 + 5.2 = 10.3

#include <stdio.h>

int  main()
{
  float a;
  float b;
  float x;

  printf("Enter the first number:\n");
  scanf("%f", &a);

  printf("Enter the second number:\n");
  scanf("%f", &b);

  x = a + b;

  /*Printing decimal number*/

  printf("Result: %.1f + %.1f = %g\n", a, b, x);

  return 0;

}

关于c - 两个数相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237045/

相关文章:

c - C语言(Linux)如何将NTP时间转换为Unix Epoch时间

编译器不允许在 C 中使用 exit() 函数

c - 我想用C语言使用文件输入/输出制作排序程序

c - 如何处理这种递归程序

在 mpir 中创建大型数组

c - 接收所有 IPv6 数据包

c - Int32转Epoch才能读取数据?! [C]

c - 为什么每次迭代都会打印两次消息?

c - 如何在没有 Visual Studio 的情况下下载和安装 Microsoft 的 Visual Studio C/C++ 编译器

c - 在 UNIX 系统 (Ubuntu 10.10) 上用 C 语言读取二进制文件