float top1 = 0;
switch ( operatr1 ) {
case '+':
top1 = num1 + num2;
break;
// ... continue with other cases here
}
然后,对于第二个 switch语句,top1 将可见并具有正确的值。
Define top1 outside the switch statement. The global top1 you define doesn't have the value you expect, because you define a new top1 inside each case statement. Your compiler should be warning you about this (actually, I think this should be an error in this case).
Further, since num1 through num4 are floats, your top1 and top2 should really also be floats, not ints
Effectively, remove int top1 from your global variables, then in your main:
float top1 = 0;
switch ( operatr1 ) {
case '+':
top1 = num1 + num2;
break;
// ... continue with other cases here
}
Then, for your second switch statement, top1 will be visible and have the correct value.
发布评论
评论(2)
在 switch 语句外部定义
top1
。您定义的全局top1
没有您期望的值,因为您在每个case
语句内定义了一个新的top1
。您的编译器应该对此发出警告(实际上,我认为在这种情况下这应该是一个错误)。此外,由于
num1
到num4
都是浮点数,因此您的top1
和top2
也应该是float< /code>s,而不是
int
s有效地,从全局变量中删除
int top1
,然后在 main 中:然后,对于第二个
switch
语句,top1
将可见并具有正确的值。Define
top1
outside the switch statement. The globaltop1
you define doesn't have the value you expect, because you define a newtop1
inside eachcase
statement. Your compiler should be warning you about this (actually, I think this should be an error in this case).Further, since
num1
throughnum4
are floats, yourtop1
andtop2
should really also befloat
s, notint
sEffectively, remove
int top1
from your global variables, then in your main:Then, for your second
switch
statement,top1
will be visible and have the correct value.您可以使用一个函数:
您的 main 将被简化为:
You could make use of a function:
Your main would be simplified to: