首页 > 解决方案 > 从 C 中的 1 个语句中查找 2 个变量的总和

问题描述

我最近开始学习 C 并且必须创建一个程序,从标准输入中扫描两个整数值,用空格分隔,然后 printf 这两个整数的总和。必须能够接受负值。我正在使用 repl.it 编写代码 1st 然后粘贴到 .c 中进行编译。

试图:

#include <stdio.h>

int main(void) {
   int j = 0;
   printf("Enter 2 integers separated by space and press enter:\n");
   while (scanf("%d", &j) == 1) { 
      printf("Here is the sum:"%d", j);
   }
   return 0;
}

除了这个打印

Here is the sum: 1Here is the sum: 2

输出错误,我犯了什么错误?获得期望值的正确方法是什么?

(例如 1+2=3)

标签: csum

解决方案


您的代码不正确。"Here is the sum:"%d"由于格式错误的字符串,它甚至无法编译。该程序将从标准输入中重复扫描一个整数并将其打印为求和的结果。

通过使用模式可以很容易地用scanf()函数来解析两个由空格分隔的整数。"%d %d"该函数scanf()返回许多成功解析的参数,因此2正确输入的值是预期的。最后,添加两个数字并打印结果。

#include <stdio.h>

int main(void) {
   int i, j;
   if (scanf("%d %d", &i, &j) == 2) { 
      printf("Here is the sum: %d\n", i + j);
   return 0;
}

推荐阅读