[英]Using characters in a conditional statement in C++
I am trying to write a program which asks for tuition credits and for undergraduate or graduate classes. 我正在努力编写一个课程,要求学费学分和本科或研究生课程。 User enters the number of credits, then must enter
U
for undergraduate or G
for graduate. 用户输入学分数,然后必须输入
U
为本科生或G
为毕业生。 I am having issues with the conditional statement, if the user enters U
, then the price of the undergraduate credits will compute and output, similar with graduate. 我对条件陈述有问题,如果用户输入
U
,那么本科学分的价格将计算和输出,与毕业生类似。 I am trying to enter U
at the IF condition, but either one price or the other outputs. 我试图在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");
}
You never give a value to U
. 你从来没有给一个价值
U
。 Right now its content is garbage which is why you get random behavior. 现在它的内容是垃圾,这就是你获得随机行为的原因。 Try either assigning
'U'
to your variable U
or changing the confiditional to: 尝试将
'U'
分配给变量U
或将confiditional更改为:
if( Second == 'U' )
Ok I see a few problems here. 好的,我在这看到一些问题。
The main one is that characters in C++ have single quotes, like this 'c'
. 主要的一点是C ++中的字符有单引号,比如
'c'
。 This is most likely the cause of your error. 这很可能是导致错误的原因。 Since you never initialized U anywhere, either do initialize it to
'U'
or try 既然您从未在任何地方初始化过U,请将其初始化为
'U'
或尝试
if ( Second == 'U' )
cout << Third ;
Second, though this is not necessarily an error typing cout<<endl<<endl;
第二,虽然这不一定是输入
cout<<endl<<endl;
is a little wasteful as it flushes the buffer for cout twice with only 1 character added in between. 有点浪费,因为它冲洗缓冲区cout两次,中间只添加了1个字符。 typing
cout<<'\\n'<<endl;
输入
cout<<'\\n'<<endl;
would fix that. 会解决这个问题。
It is more or less all of the already stated: 它或多或少都已经说明了:
char U
since it is never used char U
的声明,因为它从未使用过 Second
to char
(remove from the double
list and add char Second;
) Second
的类型更改为char
(从double
列表中删除并添加char Second;
) if ( ( Second == 'U' ) || ( Second == 'u' ) )
if ( ( Second == 'U' ) || ( Second == 'u' ) )
I don't see U = 'U'
anywhere. 我在任何地方都看不到
U = 'U'
。 You is declared at beginning, but never initialized. 您在开始时声明,但从未初始化。 You
U
is just a variable. 您
U
只是一个变量。 You have to assign the character 'U'
in it. 你必须在其中指定字符
'U'
。
第二个被声明为double,但看起来你希望用户输入一个字符。
use 采用
using namespace std;
under header file 在头文件下
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.