如何在if-else语句中声明变量?

How do I declare a variable in a if-else statement?

本文关键字:声明 变量 语句 if-else      更新时间:2023-10-16

我在这方面还是个新手,我真的不明白很多事情唯一缺少的是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的"过早优化是万恶之源"