为什么我的C程序做简单的折旧不起作用?

为什么我的C程序做简单的折旧不起作用?,c,C,我正试图用C语言编写一个程序来计算某物折旧后的残值。但是,在我运行此命令时: int main(int argc, char* argv){ printf("enter the purchase price, years of service, annual depreciation:\n"); double purchasePrice, yearsOfService, annualDep; scanf("%d %d %d", &purchasePrice, &a

我正试图用C语言编写一个程序来计算某物折旧后的残值。但是,在我运行此命令时:

int main(int argc, char* argv){
    printf("enter the purchase price, years of service, annual depreciation:\n");
    double purchasePrice, yearsOfService, annualDep;
    scanf("%d %d %d", &purchasePrice, &yearsOfService, &annualDep);
    printf("purchase price is %d dollars\n", purchasePrice);
    printf("years of service is %d years\n", yearsOfService);
    printf("annual depreciation is %d dollars\n", annualDep);
    double salvageValue = purchasePrice - (yearsOfService * annualDep);
    printf("The salvage value of the item is %d", salvageValue);

    return 0;
}

它打印出的是购买价格,而不是回收价值。发生了什么事?

将您的
scanf
呼叫替换为:

scanf("%lf %lf %lf", &purchasePrice, &yearsOfService, &annualDep);
scanf
要求所有传递的指针都匹配转换说明符的类型(反之亦然)。您正在将指针传递到
double
s,正确的转换说明符是
%lf

scanf
手册页:

l
表示转换将是d、i、o、u、x、x或n中的一个,并且 下一个指针是指向长整型或无符号长整型的指针(而不是 int),或转换为e、f或g之一,下一个指针为 指向double(而非float)的指针。需要指定两个l字符 与L等效。如果与%c或%s一起使用,则相应的参数为 作为指向宽字符或宽字符串的指针 非常感谢


(我的重点)

你能测试一下(服务年数*年数)是否为零吗?只要把它打印出来就可以了;我加上:printf(“总损失为%d\n”,(服务年限*年进度));它还打印了0,您在
scanf
调用中使用了
%d
转换说明符,但您正在向double传递指针。为什么这应该是长浮点而不是double?我试过这个;它仍然不起作用。
%lf
用于双精度,因为
%d
用于小数(即整数)。如图所示。
scanf
没有为double定义特定的转换说明符,因此必须使用
l
f
的组合,有关详细信息,请参见
man 3 scanf
。@AviG因为
printf
格式说明符
%d
也是错误的。它应该是
%f
。“d”并不意味着“双重”。顺便说一句,没有长浮点这样的东西。
scanf
“%lf”
的格式说明符意味着
double