我认为在角色上使用scanf有时会导致它被跳过。但是,我试图在整数上使用该函数,但它不起作用。任何帮助,将不胜感激。感谢
#include <stdio.h>
int main(void) {
int n1, n2, d1, d2, rn, rd;
printf("Enter first fraction\n");
scanf("%d/%d", &n1, &d1);
printf("Enter second fraction\n");
scanf("%d/%d", &n2, &d2);
rn = n1*d2 + n2*d1;
rd = d1*d2;
printf("The result is %d/%d\n", rn, rd);
return 0;
}
输出
Enter first fraction
Enter second fraction
The result is 1835042429/-1042310836
答案 0 :(得分:3)
每当使用scanf()
时,必须检查返回值以验证输入是否已正确解析为目标参数。这将告诉您输入是否有无效或缺失导致难以找到错误:
#include <stdio.h>
int main(void) {
int n1, n2, d1, d2, rn, rd;
printf("Enter first fraction\n");
if (scanf("%d/%d", &n1, &d1) != 2) {
printf("invalid input\n");
return 1;
}
printf("Enter second fraction\n");
if (scanf("%d/%d", &n2, &d2) != 2) {
printf("invalid input\n");
return 1;
}
rn = n1 * d2 + n2 * d1;
rd = d1 * d2;
printf("The result is %d/%d\n", rn, rd);
return 0;
}
编辑:您正在https://www.codechef.com/ide上运行代码:除非您检查自定义输入选项并提供实际输入,否则标准输入为空文件。您无法在此站点上以交互方式运行程序,您应该在自己的系统上安装编译器(和调试器)以更有效地学习编程。