c - 从 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)
解决方案
您的代码不正确。"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;
}
推荐阅读
- java - Payara Docker 数据源连接问题
- vb.net - 工作区在 VB.net 中显示不正确
- javascript - Multer Node.js 的文件上传 MIME 类型问题
- tensorflow - 限制屏蔽区域中的卷积计算
- json - 从文件中流式传输并解析大量 json 对象集合(不是数组)
- mysql - Grails、MySQL 和扩展类
- sql-server - 对存储在数据库 MVC 中的 pdf 文件的内容进行全文搜索
- python - 如果单词列表中的每个单词都存在于具有单词列表作为值的字典中,则返回键
- r - 在为函数“dbConnect”选择方法时评估参数“drv”时出错:找不到函数“MySQL”
- javascript - 无法使用 RecordRTC 将麦克风音频输入与屏幕录制流结合起来