发生异常。分段错误

问题描述 投票:0回答:1

在我的第一篇文章下面为课堂进行实验室工作,因此如果格式不正确,我深表歉意。

当我运行调试模式时,它将一直工作到我输入整数(非负数)的位置,然后它将冻结或崩溃并显示“发生异常。分段错误”指向该行

scanf("%lf",&usernum);

我尝试将其更改为整数,以防输出太大或其他原因,但结果是相同的。

#include <stdio.h>
#include <math.h>

#define PI 3.14159265 // PI
#define E 2.718281827 // natural constant

//Car payment calculator
int main(void)
{

     float cost;
     float interest;
     float down_payment;
     float num_of_payments;
    
    
    
    printf("Calculate loan payment:\n");
    printf("Enter cost of car:");
    scanf("%f",&cost);
    printf("Enter down payment:");
    scanf("%f",&down_payment);
    printf("Enter annual interest rate:");
    scanf("%f",&interest);
    float monthly_interest = interest/12;
    printf("Enter number of payments:");
    scanf("%f",&num_of_payments);
    
    float principle =cost-down_payment;

//payment formula

    float final_payment =(principle*monthly_interest)/(1- pow(1+monthly_interest,-num_of_payments));
    
    printf("Your monthly payment is $%.2f\n" ,final_payment);

// Facotrial approximations

    double usernum;
    double pi = 3.14159265;
    double e = 2.718281827;
    
    
    printf("Calculate Factorial\n");
    printf("Enter integer:");
    scanf("%lf",&usernum);      <----------------------------- Issue occurs here

//Gospers formula

    double factorial = pow((usernum/E),usernum)*sqrt(PI*((2*usernum))+(1/3));
    
    printf("%lf""! equals approximately %lf",usernum,factorial);

getchar();
return 0;
}
c debugging segmentation-fault
1个回答
0
投票

抱歉我无法添加评论,我会在这里询问。

你最后的输出是什么?你看到你每月的付款了吗?分段错误可能是一个棘手的错误,其原因不必与错误行位于同一行。您可能需要设置断点或简单地编写一些 printfs 来定位问题的确切位置。

为什么你的 printf 中有“$”字符?

printf("Your monthly payment is $%.2f\n" ,final_payment);

我的最后一个问题是你为什么使用 double?

我会相应地编辑我的答案。

© www.soinside.com 2019 - 2024. All rights reserved.