在C ++中使用条件语句中的字符

时间:2012-09-27 03:37:06

标签: c++ char conditional character

我正在努力编写一个课程,要求学费学分和本科或研究生课程。用户输入学分数,然后必须输入U为本科生或G为毕业生。我遇到条件陈述的问题,如果用户输入U,那么本科学分的价格将计算和输出,与毕业生类似。我试图在IF条件下输入U,但要么是一个价格,要么是其他输出。

#include <stdlib.h>                             
#include <iostream.h>                          

int main ()                                    
{                                             
 const double Under = 380.00 ; 
 const double Grad = 395.00 ;
 char U , G ; 
 double First, Second, Third, Fourth, Fifth, Sixth ;

 cout << endl << endl ;       
 cout << " To calculate your tuition enter the amount of credits, then enter type of"  ; 
 cout << endl ; 
 cout << " classes." ; 

 cout << endl << endl ; 
 cout << " Enter number of credits. " ; 
 cin >> First ; 
 cout << endl << endl ;

 cout << " Enter U for Undergraduate or G for Graduate: " ; 
 cin >> Second ; 

 cout << endl << endl ; 
 cout << " Your tuition total is: " ; 

 Third = First * Under ; 

 Fourth = First * Grad ; 

 if ( Second == U )
 cout << Third ;

 else 
 cout << Fourth ; 
 cout << endl << endl ; 

 system ("Pause");                      

 }                                               

6 个答案:

答案 0 :(得分:1)

您永远不会给U赋值。现在它的内容是垃圾,这就是你获得随机行为的原因。尝试将'U'分配给变量U或将配置更改为:

if( Second == 'U' )

答案 1 :(得分:1)

好的,我在这里看到一些问题。

主要的一点是C ++中的字符有单引号,如'c'。这很可能是导致错误的原因。由于您从未在任何地方初始化过U,因此请将其初始化为'U'或尝试

if ( Second == 'U' )
    cout << Third ;

其次,虽然这不一定是错误,但是键入cout<<endl<<endl;会有点浪费,因为它会刷新cout缓冲区两次,中间只添加1个字符。输入cout<<'\n'<<endl;可以解决这个问题。

答案 2 :(得分:1)

或多或少已经说明了所有内容:

  1. 删除char U的声明,因为它从未使用
  2. Second的类型更改为char(从double列表中删除并添加char Second;
  3. 将if语句更改为if ( ( Second == 'U' ) || ( Second == 'u' ) )

答案 3 :(得分:0)

我在任何地方都看不到U = 'U'。您在开始时声明,但从未初始化。你U只是一个变量。您必须在其中指定字符'U'

答案 4 :(得分:0)

第二个被声明为double,但看起来你希望用户输入一个字符。

答案 5 :(得分:-1)

使用

Private Sub text_box_a_GotFocus()
    Me.list_ctrl.Visible = True
End Sub

Private Sub list_ctrl_LostFocus()
    If Not (Me.text_box_a Is Me.ActiveControl) Then
        Me.list_ctrl.Visible = False
    End If
End Sub

在头文件下