【问题标题】:Simple C calculator error简单的 C 计算器错误
【发布时间】:2012-10-13 06:02:57
【问题描述】:

我正在尝试制作一个简单的 c 计算器,因为我是一个新手,并且认为这将是一个好主意。这是我的代码:

#include <stdio.h>
main()
{
 char b;
 int a,c,d;
 printf("Please enter your first number: ");
 scanf("%d",&a);
 printf("Please enter your second number: ");
 scanf("%d",%c);
 printf("Enter your operation");
 scanf("%c",&b);
 if (b == 'a')
 {
     d = a + c;
     printf("The answer is: %d",d);
 }
}

当我编译代码时,这是我得到的错误/警告:

D:...|4|warning: return type defaults to 'int'|
D:...||In function 'main':|
D:...|10|error: expected expression before '%' token|

有人可以帮忙吗?

【问题讨论】:

  • 将main() 声明为int main(void) 并从中返回0。

标签: c scanf calculator


【解决方案1】:

在scanf 中将% 更改为&amp;:

scanf("%d", &c);
            ^

另外,你想要int main 而不是main,你可能应该在最后返回一些东西。

【讨论】:

  • 自 C99 以来,从 main 返回某些内容不是强制性的。如果在没有返回的情况下到达 main 的末尾,则将返回 0。见 C99 5.1.2.2.3:[...] reaching the } that terminates the main function returns a value of 0.
  • 我也经常这样做 :)。只是想澄清一下
【解决方案2】:

使用 & 运算符代替 % 运算符。& 运算符用于访问特定变量的地址,因此也称为地址运算符。有关详细信息,请访问: https://www.techopedia.com/definition/25580/address-of-operator--c

【讨论】:

    【解决方案3】:

    比较这两行,你告诉我们有什么区别:

    scanf("%d",&a);
    scanf("%d",%c);
    

    【讨论】:

      猜你喜欢
      • 2013-12-31
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多