【问题标题】:Use of ampersand in C programming [duplicate]在 C 编程中使用 & 符号 [重复]
【发布时间】:2016-07-16 07:59:14
【问题描述】:

我的代码:-

#include<stdio.h>
#include<conio.h>
void main(){
    int a,b,c;
    printf("Enter the 1st number:");
    scanf("%d",a);
    printf("Enter the 2nd number:");
    scanf("%d",b);
    c=a*b;
    printf("The value of %d * %d is %d",a,b,c);
    getch();
}

现在当我在 Turbo C++ 中执行这个程序时,输出如下:-

Enter the 1st number:10
Enter the 2nd number:10
The value of 1308 * 1320 is 22625

为什么会这样?

【问题讨论】:

  • 你还没有传递 scanf 指针。在 scanf 行的“a”和“b”前面添加一个 & 符号。您的标题表明您已经知道这是问题所在。
  • 对于所有 scanf() 语句,@EJP、scanf("%d",a); 应该是 scanf("%d",&amp;a); 等等。
  • 是的@Borealid我一开始就知道&符号是问题,但我想知道&符号的作用以及没有&符号系统采用的值如何变为1308和1320对于'a'和' b'分别?很抱歉没有在问题本身中提及这一点。也许我应该在发布之前检查我的问题的写作。

标签: c


【解决方案1】:

在从用户获取值时,您缺少 &amp; 和号。您必须获取变量地址中的值,而不是变量本身,因此请使用&amp;,同时在scanf 函数中从用户那里获取值。

#include<stdio.h>
#include<conio.h>
void main(){
    int a,b,c;
    printf("Enter the 1st number:");
    scanf("%d",&a);
    printf("Enter the 2nd number:");
    scanf("%d",&b);
    c=a*b;
    printf("The value of %d * %d is %d",a,b,c);
    getch();
}

【讨论】:

  • 谢谢!这很有帮助:)。但是你能告诉我一件事,当我没有放置&符号时,'a'和'b'的值如何分别变为1308和1320?效果如何?
  • @Arko991 它们是你记忆中的垃圾值。您没有为它们分配任何值并对它们进行算术运算,因此它正在从该位置的内存中获取垃圾值。
  • 好的,我明白了,但还有一件事,这些垃圾值是随机的吗?意思是如果我再次执行没有与号的程序,值(1308 和 1320)是否相同,或者它会为“a”和“b”提供另一个值?
  • @Arko991 垃圾值总是随机的,具体取决于 IDE 为变量提供的地址。
  • 谢谢。我现在明白了。 :)
猜你喜欢
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 2017-05-27
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多