[英]Using scanf in Objective-C will not assign to an integer?
我知道我需要将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;
应该在你的 NSLog 之前。
当您在开头说int c = a * b
时,会发生以下情况:
由于 int a 没有初始化,它被赋予一个随机垃圾值,与 b 相同。 然后您立即分配 c 两个垃圾值的乘积。
当您将 c 初始化为 c=a+b 时,此时 a 和 b 的值为零,因此它将 c 存储为零。 之后,通过使用 scanf 将您的读数值添加到 a 和 b。 现在,如果您打印 c 值,则该值为零,这就是它所显示的。 如果你想要正确的结果,你必须在阅读 a 和 b 之后放置语句 c=a+b。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.