c - 我无法让 if 语句正确执行

标签 c

我似乎无法让我的 if 语句在程序的存款和取款部分正确执行。当数字为负数时,它会正确执行,但当数字为正数时,它会显示错误消息,然后结束循环并转到提款。

#include <stdio.h>
int main (void)
{
    int deposits = 0, totaldeposits = 0, deposited = 0, totalwithdrawals = 0, withdrawals, d = 0, w = 0;
    float balance = 0, b;

        printf ("Welcome to the computer banking system\n\n");

    for ( b = 0; b <= balance; ++b )
    {
        printf ("Enter your current balance in dollars and cents:");
            scanf ("%f", &b);
            balance = balance + b;

        if ( balance <= -1 )
        {
            printf ("***Beginning balance must be at least zero, please re-enter.\n\n");
                balance = balance - b, --b;

        }/*end of if statement*/
    }/*end of for loop*/

    for ( d = 0; d <= deposits; ++d )
    {       
        printf ("\nEnter the number of deposits (0-5):");
            scanf ("%i", &d);
        deposits = deposits + d;

        if ( deposits > 5 || deposits < 0 )
        {
            printf ("*** Invalid number of deposits, please re-enter.");
                deposits = deposits - d;
        }/*end of if statement for deposits*/       
    }/*end of for loop for deposits*/
    for ( w <= 0; w <= withdrawals; ++w)
    {
        printf ("\n\nEnter the number of withdrawals (0-5):");
            scanf ("%i", &w);
            withdrawals = withdrawals + w, ++w;

        if ( withdrawals > 5 || withdrawals < 0 )
        {
        printf ("***Invalid number of withdrawals, please re-enter.");
        withdrawals = withdrawals - w, --w;
        }/*end of withdrawals if*/
    }/*end of withdrawals for loop*/





getchar;        
return 0;

} /*End main*/

最佳答案

你的程序逻辑似乎有一些错误。我会重写

for ( d = 0; d <= deposits; ++d )
{       
    printf ("\nEnter the number of deposits (0-5):");
        scanf ("%i", &d);
    deposits = deposits + d;

    if ( deposits > 5 || deposits < 0 )
    {
        printf ("*** Invalid number of deposits, please re-enter.");
            deposits = deposits - d;
    }/*end of if statement for deposits*/       
}/*end of for loop for deposits*/

作为

do {
    printf ("\nEnter the number of deposits (0-5):");
    scanf ("%i", &deposits);

    if (deposits < 0 || deposits > 5) {
        printf ("*** Invalid number of deposits, please re-enter.");
    } else {
        break;
    }
} while (1);

对于其他循环也可以执行相同的操作。

其想法是至少要求输入一次,并检查输入的值对于您的情况是否有效,如果无效,则再次要求输入。

关于c - 我无法让 if 语句正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327792/

相关文章:

c - C 中指针类型转换的语法

c - 如何仅区分源文件?

c - 如何将数组从汇编程序发送到 C++

c - 我如何最好地使用 C 中的 const 关键字?

c - 从 C 中的函数返回整数数组

c - 通过 C 中的 Netlink 从内核到用户空间的多播

c - 使用带有答案的指针在 C 中创建动态数组

c - 为什么我的代码有效? C中的数组排序

c - 可移植一致浮标

c - 将函数的局部变量传递回其参数