[英]Using scanf in Objective-C will not assign to an integer?
I know that i need to assign int a
and int b
to something but i replaced it with the scanf
functions example ( int a = scanf("%d", a);
and int b = scanf("%d", b);
but that did not work so i kept it as original like shown.我知道我需要将
int a
和int b
分配给某些东西,但我将其替换为scanf
函数示例( int a = scanf("%d", a);
和int b = scanf("%d", b);
但这不起作用,所以我保持原样,如图所示。
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
int a ;
int b ;
int c = a * b;
printf("Welcome to the multiplication calculator");
printf("\n");
printf("what would you like to choose for first value?");
scanf("%d", &a);
printf("\n");
printf("What would you like to input for the second value?");
scanf("%d", &b);
printf(" Here is your product");
printf("\n");
NSLog(@"a * b =%i", c);
return 0;
}
int c = a * b;
Should be right before your NSLog.应该在你的 NSLog 之前。
When you say int c = a * b
at the beginning here is what happens:当您在开头说
int c = a * b
时,会发生以下情况:
Since int a is not initialized, it is given a random garbage value, same with b.由于 int a 没有初始化,它被赋予一个随机垃圾值,与 b 相同。 Then you immediately assign c the product of the two garbage values.
然后您立即分配 c 两个垃圾值的乘积。
While you'r initializing c as c=a+b at that time the values of a and b are zeros so its storing c to zero.当您将 c 初始化为 c=a+b 时,此时 a 和 b 的值为零,因此它将 c 存储为零。 After that by using scanf your reading values to a and b.
之后,通过使用 scanf 将您的读数值添加到 a 和 b。 Now if you print c value the value is zero thats what it is showing.
现在,如果您打印 c 值,则该值为零,这就是它所显示的。 If you want proper result you have to put the statement c=a+b after reading a and b.
如果你想要正确的结果,你必须在阅读 a 和 b 之后放置语句 c=a+b。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.