问题描述
我是C编程的新手,我陷入了一个简单的问题。这是以下代码...
#include <stdio.h>
/* Write a C Program that accepts two integers from the
user and calculate the sum of the two intergers. Go to the editor!
*/
int main()
{
int firstInteger,secondInteger;
int sum;
printf("Input two Integers: \n");
scanf("%d%d",&firstInteger,&secondInteger);
sum = firstInteger + secondInteger;
printf("%d",sum);
return 0;
}
在GCC编译器上运行代码后,我没有得到期望的结果!
C:\XXXX\XXXX\XXXX\XXXX\XXXX>gcc 2sumOfTwoIntegers.c
C:\XXXX\XXXX\XXXX\XXXX\XXXX>a
Input two Integers:
25,38
25
为什么我没有得到我输入的整数的总和?
解决方法
您正在输入逗号。只需放一个空格 像那样 25 38
,您有两种方法可以解决此问题-
- 删除输入的两个整数之间的','。只需输入以下内容即可:25 38。
- 如果要在输入整数之间输入',',则需要在代码中进行更改。在scanf行中,您应该输入:
scanf("%d,%d",&firstInteger,&secondInteger);
[注意:您在%d中输入的内容将在输入部分中跳过。就像您想在两个变量中使用两个整数小时和分钟。然后您可以编写:
scanf("%d:%d",&hour,&minute);
因此,如果您在输入部分中输入-10:30,则小时变量取10,分钟变量取30。 ]
,您期望用户将使用两个整数之间的逗号输入。用户可以输入两个整数,例如
25,38
或
25,38
所有这些输入均有效。您需要正确处理输入。
您需要的是跳过两个数字之间的逗号。
还要考虑到两个整数之和可能太大而无法存储在int类型的对象中。
这是一个执行任务的演示程序。
#include <stdio.h>
int main(void)
{
int firstInteger,secondInteger;
printf( "Input two Integers (first,second): " );
if ( scanf( "%d %*c %d",&secondInteger ) == 2 )
{
long long int sum = ( long long int )firstInteger + secondInteger;
printf( "The sum of the integers is %lld\n",sum );
}
else
{
puts( "Incorect input." );
}
return 0;
}
其输出可能看起来像
Input two Integers (first,second): 25,38
The sum of the integers is 63
另一种方法是读取变量中的逗号,并检查用户是否确实键入了逗号。在这种情况下,程序看起来像
#include <stdio.h>
int main(void)
{
int firstInteger,secondInteger;
char c;
printf( "Input two Integers (first,second): " );
if ( scanf( "%d %c %d",&c,&secondInteger ) == 3 && c == ',' )
{
long long int sum = ( long long int )firstInteger + secondInteger;
printf( "The sum of the integers is %lld\n",sum );
}
else
{
puts( "Incorect input." );
}
return 0;
}
,
scanf()
默认情况下不要跳过输入中的,
并在此停止,因为它不能解释为整数。
将,
添加到这种格式,以使scanf()
读取并删除,
。
scanf("%d,&secondInteger);