C switch语句,变量错误(计算器程序源代码)

发布于 11-14 19:58 字数 1778 浏览 2 评论 0原文

你好,今天当我尝试一些新的东西(突然在我脑海中浮现的概念和风格)时,我遇到了一些问题,我不明白为什么会发生。

代码

// This program would get two numbers from user , and request for an arithmetic operator , and carry out arithmetic.

 #include <stdio.h>


int main(void)
{
    int fNum;
    int sNum;
    int status = 1;
    int operator;
    int ans;

    printf("Enter the first operand :");
    while(scanf("%d" , &fNum) == 0)
        ;
    printf("Please enter the second operand :");

    while(scanf("%d" , &sNum) == 0)
        ;    
    printf("Which operator you wanted to use\n");
    printf("1 for +\n2 for -\n");


   while(status)
   {

     scanf("%d" , &operator);
     status = 0;

     switch(operator)
     {
           case 1:
             ans = fNum + sNum;
              break;

           case 2:
             ans = fNum - sNum;
             break;

           default:
             status = 1;
     }
   }
   
    printf("The answer is %d\n" , ans);
             
    return 0;
}

我的分析和问题

第一部分:

1.)有件事我不明白,当我尝试运行此代码时,我收到一条警告消息编译器,“C:\Users\Znet\Documents\Pelles C Projects\Test1\Test.c(10):警告#2229:本地“ans”可能在未初始化的情况下使用。” ,但当然我仍然可以运行该程序,因为它不是错误消息。

2.)出于好奇,我只是想知道为什么会出现此警告消息,而不是仅仅声明变量 ans ,而是使用整数值(0 或任何整数)和警告消息来初始化它是什么原因导致这种情况发生?是不是因为 ans 变量被用在 switch 语句中,所以我们应该在使用它之前为其赋值?因为一直(当我编码时其他程序)在使用变量存储由算术表达式计算的值之前,我什至不使用值初始化变量。

第二部分:

1.)当程序要求用户输入数字12作为开关时,问题出现在switch语句中。算术符号。

2.)如果我输入一个不在1和2之间的整数,程序将不会继续,而是等待我重新输入正确的值,这是我的主要意图。

3.)但问题是,如果我输入的值不是整数而是字符,程序就会冻结,光标仍然闪烁,但它不响应我的键盘输入。最后,我必须杀死程序以便将其关闭。

4.)我知道我有很多方法可以编写这种程序,但我只是想知道为什么在这段代码中,会发生这种情况?



感谢您阅读我的问题,希望得到你们的解释和知识:)

Greetings , today when I try something new(Concept and style that suddenly pop out in my mind) , I encountered a few problems which I don't understand why it happened.

The Code

// This program would get two numbers from user , and request for an arithmetic operator , and carry out arithmetic.

 #include <stdio.h>


int main(void)
{
    int fNum;
    int sNum;
    int status = 1;
    int operator;
    int ans;

    printf("Enter the first operand :");
    while(scanf("%d" , &fNum) == 0)
        ;
    printf("Please enter the second operand :");

    while(scanf("%d" , &sNum) == 0)
        ;    
    printf("Which operator you wanted to use\n");
    printf("1 for +\n2 for -\n");


   while(status)
   {

     scanf("%d" , &operator);
     status = 0;

     switch(operator)
     {
           case 1:
             ans = fNum + sNum;
              break;

           case 2:
             ans = fNum - sNum;
             break;

           default:
             status = 1;
     }
   }
   
    printf("The answer is %d\n" , ans);
             
    return 0;
}

My Analysis and Question

First part :

1.)There's one thing I don't understand , when I try to run this code , I get an warning message from the compiler , "C:\Users\Znet\Documents\Pelles C Projects\Test1\Test.c(10): warning #2229: Local 'ans' is potentially used without being initialized." , but of course I still can run the program since it's not an error message.

2.)I just wonder why this warning message occured , out of curiosity , instead of just declaring the variable ans , I initialize it with an integer value(0 or any whole number) , and the warning message just gone.What causes this to happen??Is it because the variable ans is used in a switch statement that's why we should assign a value to it before using it?Because all the time (when i'm coding other program) I don't even initialize a variable with a value before using it to store a value evaluated by an arithmetic expression.

Second part :

1.)The problem arouse inside the switch statement , when the program is asking user to enter either number 1 or 2 for the arithmetic sign.

2.)If i enter an integer not within 1 and 2 , the program will not proceed but instead waited me to reenter the correct value , which is my main intention.

3.)But the thing is , if the value I enter is not an integer but instead a character , the program would just freeze , the cursor is still blinking but it's not respond to my keyboard input.In the end , I have to kill the program in order to close it.

4.)I know there're many ways for me to code this kind of program , but I just wonder why in this code , this situation would happened??

Thanks for reading my problem , hope to get explanations and knowledges from you guys :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不及他2024-11-21 19:58:24

第一个问题:

编译器检测到 ans 仅获取有条件分配给它的值(对于 switch 语句中的两种特定情况)。有些编译器会对此发出警告,而另一些则不会。通常,初始化您创建的任何变量始终是一个好习惯。

第二个问题:

这个问题之前已经回答过很多次了 - 请参阅无限 scanf 循环。问题是 scanf 在这种情况下只接受整数。正如此链接中提到的“任何与格式字符串不匹配的字符都会导致其停止扫描并将无效字符保留在缓冲区中。”这导致您的 while 循环永远不会退出。如果您对更多详细信息感兴趣,这里提到的链接应该会对您有所帮助。

First question:

The compiler is detecting that ans is only getting a value assigned to it conditionally (for two specific cases in your switch statement). Some compilers warn about this and others do not. As a rule, it is always good practise to initialize any variable you create.

Second question:

This question has been answered many times before - see infinite scanf loop. The problem is that scanf only accepts an integer in this case. As mentioned in this link "Any character that doesn't match the format string causes it to stop scanning and leaves the invalid character still in the buffer." This is causing your while loop to never exit. If you are interested in more details, the link mentioned here should really help you.

但可醉心2024-11-21 19:58:24
    • 问:“警告 #2229:本地“ans”可能在未初始化的情况下被使用。”

    • A:这意味着 ans 可以在声明时包含任何值(因为堆栈变量在声明时不会被清空) - 并且因为编译器没有看到保证在打印时设置变量的编程逻辑- 它会抛出此警告。执行 int ans = 0; 将删除它。

    • 问:如果我输入的值不是整数而是字符,程序就会冻结,光标仍然闪烁,但不响应我的键盘输入。最后,我必须杀死程序以便将其关闭。

    • 一个

.

do { 
    printf("Which operator you wanted to use\n");
    printf("1 for +\n2 for -\n");
} while ( scanf("%d", &operator) != 1 );

scanf 返回匹配的数量 --- 如果不匹配整数,则返回 0。因此;检查返回值。

    • Q: "warning #2229: Local 'ans' is potentially used without being initialized."

    • A: This means that ans can contain any value upon declaration (since stack variables aren't nulled out on declaration) - and since the compiler didn't see programming logic that guarantees that the variable is set when printed - it throws this warning. Doing int ans = 0; will remove it.

    • Q: If the value I enter is not an integer but instead a character , the program would just freeze , the cursor is still blinking but it's not respond to my keyboard input.In the end , I have to kill the program in order to close it.

    • A

.

do { 
    printf("Which operator you wanted to use\n");
    printf("1 for +\n2 for -\n");
} while ( scanf("%d", &operator) != 1 );

scanf returns the amount of matches --- if it doesn't match an integer, it will return 0. Therefore; Check the return value.

Bonjour°[大白2024-11-21 19:58:24

第一部分

当您在未显式初始化的情况下使用变量时, 编译器可能会发出警告。这是因为未初始化的变量可能会在代码中产生严重的错误。例如,考虑以下代码段。

int main()
{
   /* NOTE: 'f' is uninitialized */
   int f, n;

   printf ("\nn : ");
   scanf ("%d", &n);

   while (n)
    f = f * n--;

   printf ("\nfactorial = %d", f);
   return 0;
}

在上面的代码中,程序的输出未定义。 f 是一个局部变量(automatic),因此当 main 开始执行时,f 可以有任何值,即垃圾,阶乘计算依赖于f的初始值。所以在这种情况下,未初始化的变量将会导致灾难。要解决这个问题,您需要执行 int f = 1; 并获得正确的输出。这不是一个错误,但可能是一个逻辑错误,因此编译器会帮助您解决这个问题,这样您就不会意外地留下未初始化的变量。在您的情况下,不需要初始化,因此您只需执行 ans = 0; 即可停止警告。

第二部分

字符和整数的解释不同。例如12是两个字符,我们也可以说它是一个整数。要将其作为整数输入,您应该使用 "%d" 和字符 scanf ("%c%c",&var1, var2); 因为有两个人物。当你输入一个字符时,如果格式字符串是"%d",它会检测到输入的不是一个整数(它是一个字符),并会在那一刻停止并返回。 operator 变量中不会存储任何内容。 scanf 返回它已读取的组件数。在这种情况下,当它遇到您输入的字符时,它将返回 0,因为它尚未读取输入并已停止。但是,当您输入整数时,它会在 operator 中正确读取并返回 1。因此,请进行如下检查:

/* Ask for input while the user does not input a 
 * valid integer.
 */
while (scanf ("%d", &operator) != 1)
{
   /* Body is entered whenever an invalid integer is entered */
   /* Your message */
}
/* When the user inputs a valid integer the condition 
 * in 'while' loop is false and program continues 
 */
   

First Part

Compilers can give warning when you use a variable without having it explicitly initialized. This is because uninitialized variables can create nasty bugs in your code. For example consider the following code segment.

int main()
{
   /* NOTE: 'f' is uninitialized */
   int f, n;

   printf ("\nn : ");
   scanf ("%d", &n);

   while (n)
    f = f * n--;

   printf ("\nfactorial = %d", f);
   return 0;
}

In the above code the output of the program in undefined. f is a local variable (automatic), so when the main starts to execute f can have any value, ie garbage, and the factorial computation relies on the initial value of f. So in such a case uninitialized variable will lead you to a catastrophe. To solve it you need to do int f = 1; and you get the correct output. This is not an error, but can be a logical error, so the compilers help you with it, that you might not accidentally left a variable uninitialized. In your case it is not required to be initialized, so you can simply do ans = 0; stop the warning.

Second Part

A character and an integer is interpreted differently. For example 12 are two characters, and also we can say that it is an integer. To input it as an integer you should use "%d" and as characters scanf ("%c%c",&var1, var2); as there are two characters. When you enter a character when the format string is "%d" it will detect that the input is not an integer (it is a character), and will stop at that moment and will return. Nothing will be stored in the operator variable. The scanf returns the number of components it has read. In this case when it encounters that you have entered a character it would return 0 as it has not read in the input and has stopped. But when you input an integer it will read it correctly in operator and return 1. So keep a check like:

/* Ask for input while the user does not input a 
 * valid integer.
 */
while (scanf ("%d", &operator) != 1)
{
   /* Body is entered whenever an invalid integer is entered */
   /* Your message */
}
/* When the user inputs a valid integer the condition 
 * in 'while' loop is false and program continues 
 */
   
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文