CodeChef ATM 简单级别 : Uses Casting, 条件。代码不被接受

标签 c casting floating-point conditional-statements floating-point-conversion

我对 C 中的类型转换有一点疑问。以下问题涉及基本类型转换和/或条件逻辑。

所以,我刚刚开始在 CodeChef 上解决基本问题,以使学习编码变得有趣,并且我正在尝试解决以下“简单”问题:( http://www.codechef.com/problems/HS08TEST )。

我相信我也应该在这里为 SO 社区引用这个问题:

Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction.

Input Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw. Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance.

Output Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.

Example - Successful Transaction Input: 30 120.00 Output: 89.50

Example - Incorrect Withdrawal Amount (not multiple of 5) Input: 42 120.00 > Output: 120.00

Example - Insufficient Funds Input: 300 120.00 Output:120.00

我想如何通过将整数转换为 float 来做到这一点?。我知道定义浮点变量的方法,如其他人提交的解决方案中所示(即将余额声明为浮点类型),但我仍然想知道为什么不能这样吗?(将余额声明为 int 并稍后将其转换为 float)。

代码在本地 IDE 上编译和执行良好,但不被接受。那么我有什么地方出错了吗?

这是非常简单的代码:

#include<stdio.h>
int main()
{
 int amt , bal ;
 float result;
 scanf("%d %d", &amt, &bal );
 if( ( 0 < amt <= 2000 ) && ( 0 <= bal <= 2000 ) ) //CORRECTED.SEE EDIT.
 {
    if ( ( amt % 5 !=0 ) || ( bal <= amt+1) )
    {
        result=(float)bal;
        printf("%.2f",result);
        return 0;
    }
    else
    {
        result = (float) (bal-amt-0.50);
        printf("%.2f",result);
    }
}   
return 0;
}

请告诉我逻辑是否有错误。

编辑:我将关系运算符更改为 'if((amt>0)&&(amt<=2000)&&(bal>=0)&&(bal<=2000))',但仍然没有效果。它仍然显示错误答案...

最佳答案

  0 < amt <= 2000 

不,这不是在 C 中使用关系运算符的方式。您需要将其分解为两个单独的条件检查。

类似的东西

if ( (0 < amt) && (amt <= 2000))....

其他情况也类似。

关于CodeChef ATM 简单级别 : Uses Casting, 条件。代码不被接受,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30290733/

相关文章:

char * 字符串转换为十六进制 uint8_t 值以修改 .hex 文件

c - 带有指向函数指针的结构

c++ - C++中的类型转换和引用

c++ - 将 Eigen::ArrayXXd 转换为 Eigen::MatrixXd

Javascript 停止自动舍入

ios - 在 C 包装器中获取 Objective-C 值(Unity 插件)

c - 如何通过pid获取进程的路径并重新启动它 - c

c# - 显式转换 XAttribute 值

javascript - 处理大数时的中点 'rounding'?

java - 360 度的正弦值非零