繁体   English   中英

导致分段错误的简单C程序

[英]Simple C Program Causing Segmentation Fault

我只是在学习C,并且试图编写一个简单的程序来进行简单的计算。 该程序可以正常编译,但是当我输入值并尝试运行它时,出现“段错误”。 有人可以帮我了解为什么会这样,以及细分错误到底是什么吗?

码:

#include <stdio.h>

float main()
{
  int price, service;
  float annual, value;

  printf("Enter the purchase price, years of service, annual depreciation:\n");
  scanf("%d %d %f\n", price, service, annual);

  value = (annual * service) - price;

  printf("The salvage value of the item is %f", value);
  return 0;
}

任何帮助都将不胜感激! 谢谢!

这是错的

 scanf("%d %d %f\n", price, service, annual);

应该:

 scanf("%d %d %f\n", &price, &service, &annual);

您的程序有两个问题。 首先, main()应该返回一个int值,对于成功而言通常为零,对于失败而言则为其他值。 float main ()更改为int main() ,看看是否有区别。

其次,正如其他两个答案所指出的那样,您对scanf()参数应为将保存输入值的变量的地址:

scanf("%d %d %f\n", &price, &service, &annual);

更改

scanf("%d %d %f\n", price, service, annual);

scanf("%d %d %f", &price, &service, &annual);

因为scanf总是期望使用指针作为其参数。 还要从scanf()格式说明符中删除\\n ,并将float main()更改为int main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM