Har*_*EST 0 c++ if-statement function
我对这些If/Else语句的语法做错了什么我很确定它与我的大括号放置有关.我书中的所有例子都只包含非常原始/简单的例子(并不是说这段代码不简单; b/c就是这样).我想我的一般问题也是你如何将这两个单独的陈述分开.当我执行时,似乎两个独立的函数混合在一起.
//
tens = rand / 10;
if (tens = 2){
cout << "twenty ";
else if (tens = 3)
cout << "thirty ";
else if (tens = 4)
cout << "forty ";
else if (tens = 5)
cout << "fifty ";
else if (tens = 6)
cout << "sixty ";
else if (tens = 7)
cout << "seventy ";
else if (tens = 8)
cout << "eighty ";
else if (tens = 9)
cout << "ninety ";
}
//
ones = rand % 10;
if (ones = 0){
cout << "\n";
else if (ones = 1)
cout << "one\n";
else if (ones = 2)
cout << "two\n";
else if (ones = 3)
cout << "three\n";
else if (ones = 4)
cout << "four\n";
else if (ones = 5)
cout << "five\n";
else if (ones = 6)
cout << "six\n";
else if (ones = 7)
cout << "seven\n";
else if (ones = 8)
cout << "eight\n";
else if (ones = 9)
cout << "nine\n";
}
Run Code Online (Sandbox Code Playgroud)
我认为,对于这个特殊的问题,如果 -甚至不需要!
我宁愿推荐这个解决方案:
const char *stens[] = {"", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninty"};
const char *sones[] = {"", "one", "two", "three", "four", "five",
"six", "seven", "eigth", "nine"};
//make sure 0<= rand <= 99
cout << stens[ rand / 10 ] << " " << sones[ rand % 10 ] << endl;
Run Code Online (Sandbox Code Playgroud)
在线演示:http://www.ideone.com/K7HxS
至于if-else面临的问题,你正在使用赋值运算符,而不是平等,正如每个人已经指出的那样.
单个等号是一个赋值,而不是对相等性的测试.
你应该使用ones == N一些数字N.
你似乎没有正确使用大括号({和}),你的if陈述应该是这样的:
tens = rand / 10;
if (tens == 2){
cout << "twenty ";
}else if (tens == 3){
Run Code Online (Sandbox Code Playgroud)
注意在之前else和之后的括号3).
另外,我建议switch在这种情况下使用一个语句,它可能会导致一些更容易阅读和更易于管理的代码:
tens = rand / 10;
switch(tens){
case 2: cout << "twenty "; break;
case 3: cout << "thirty "; break;
case 4: cout << "fourty "; break;
// ...
case 9: cout << "ninety "; break;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1790 次 |
| 最近记录: |