首页 > 解决方案 > 如何重新初始化变量(CCS 102)(程序 C)

问题描述

在为我们的计算器项目取得进展并重写了大部分代码之后,我遇到了一个问题。

正如标题所示,我需要帮助在循环后或每个循环中重新初始化变量。

问题:

在此处输入图像描述

它应该像这样:

在此处输入图像描述

如您所见,它仍然计算而不是提示错误,表明输入的 int 存储在我的变量中。我可能错了或其他什么,但如果我不能解决这些问题,我会取得更大的进步。

这是代码:

#include <stdio.h>
#include <stdbool.h>

//bool function
bool isInteger(double val)
{
    int truncated = (int)val;
    return (val == truncated);
}
int main(int argc, char *argv[])
{
    //local variable
    double a, b;
    char operation, option = 'y';
    
    //loop
    while(option == 'y' || option == 'Y')
    {
        //system("cls");
        printf("Enter number and operator to solve:\n\nExapmple [a + b][a - b][a * b][a / b]\n");
        scanf("%lf %c %lf", &a, &operation, &b);
        
        // nested if
        if(isInteger(a) && isInteger(b))
        {
            if(operation == '+')
            {
                printf("Result: %.1lf\n\n", a + b); //ouput result
            }
            else if(operation == '-')
            {
                printf("Result: %.1lf\n\n", a - b); //ouput result
            }
            else if(operation == '*')
            {
                printf("Result: %.1lf\n\n", a * b); //ouput result
            }
            else if(operation == '/')
            {
                printf("Result: %.1lf\n\n", a / b); //ouput result
            }
            else
            {
                //output error
                printf("Invalid Operater!\n");
            }
        }
        else
        {
            //output error
            printf("Input is not a digit!\n");
        }
        //output selection
        printf("Do you want to retry [y]/[n]?");
        option = getch(); //not recommended but just a small project
        //scanf("%c", &option); -- stops the loop
    } //end loop
}

标签: c

解决方案


在你的第二个例子中(即第二次),这条线

scanf("%lf %c %lf", &a, &operation, &b);

尝试将a读入 double ,这将导致scanf失败并提前返回。

检查文档,scanf您会看到它返回读取的值的数量,并将errno在失败时设置。这些必须在之前检查aoperation并且b可以安全使用。


推荐阅读