如何在if-else语句中声明变量?
How do I declare a variable in a if-else statement?
我在这方面还是个新手,我真的不明白很多事情唯一缺少的是x=d/t,我不知道把它放在哪里…我已经尝试了各种方法,但还是不知道该把它放在哪里。
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int d, t, s, z;
cout<<"Enter the distance of your destination:"<<endl;
cin >>d;
cout<<"Enter the time you want to get there:"<<endl;
cin >>t;
for (z=1; z<=5; z++)
{
cout<<"Enter your speed:"<<endl;
cin>>s;
if (int x=d/t && x>=s)
{
cout<<"Maintain your speed it is the appopriate speed: "<<s<<"mph"<<endl;
break;
}
else
{
cout<<"Go faster at this rate you won't get to your destination on time"<<endl;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
The Output always shows the if statement even though it should already show the else statement..
I really need help on this..
把它放到if
int x = d / t;
if (x && x >= s)
或者你想要这个
int x = d / t;
if (x >= s)
这是代码:
int main(int argc, char *argv[])
{
int d, t, s, z;
cout<<"Enter the distance of your destination:"<<endl;
cin >>d;
cout<<"Enter the time you want to get there:"<<endl;
cin >>t;
for (z=1; z<=5; z++)
{
cout<<"Enter your speed:"<<endl;
cin>>s;
int x=d/t;
if (x>=s)
{
cout<<"Maintain your speed it is the appopriate speed: "<<s<<"mph"<<endl;
break;
}
else
{
cout<<"Go faster at this rate you won't get to your destination on time"<<endl;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
改为:
int x=d/t;
if(x && x>=s)
{
// ...
你不能这么做。
如果你想完全做到你所写的,使用这个:
int x = d/t;
if (x && x >= s)
{
...
}
但你可能只是想要:
if(x >= s)
Try
int x = d/t;
if (x >= s) {
....
根据一本关于c++的书
为什么要声明x ?
if(d/t>=s)
我猜你的问题是输入数据(距离,时间)应该是double
,而不是int
。在c++中,整数除法截断,即2 / 3 == 0
。已经把我甩了好几次了…整数是用来计数的,不是用来测量的。
不要担心写一些表达式几次,现在的编译器足够聪明,可以注意到并计算一次。在任何情况下,尽可能编写最简单、最清晰的代码。只有当这显示太慢(不太可能)时,才值得仔细检查代码以加强它。你写代码的时间,当它出错时,理解它到底写了什么,并修复它,比几秒钟的计算机时间更有价值。
永远不要忘记Brian Kernighan的"调试是编写代码的两倍难"。因此,如果你尽可能聪明地编写代码,从定义上讲,你还不够聪明,无法调试它。"还有Donald Knuth的"过早优化是万恶之源"
相关文章:
- 在疯狂的部分中声明变量
- 如何在C++中为高分辨率时钟声明变量?
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- CUDA 的性能取决于声明变量
- 如何在不为其声明变量的情况下获取和使用常量值的地址?
- C++声明变量时自动类型推断而不初始化
- 在不同循环中多次声明变量的优点
- 奇怪的错误 C2131 与 constexpr 声明变量
- 是否可以在 "if" 语句中声明变量?
- 在python-ctypes中声明变量并传递给dll函数
- 在递归函数C++中声明变量
- 只有一个定义/声明时标头声明变量的多堆定义错误
- 奇怪的未声明变量编译器错误
- 我在C++程序中声明变量时遇到问题
- 在命名空间中声明变量
- C++ lambda 按值捕获,而无需更早声明变量
- 声明变量以保存字符串列表时的内存分配
- 如何声明C 变量应突变
- 为什么允许在开关语句中声明变量?但不是声明 初始化
- 在同一命名空间中声明变量和函数是否出错?[C++]