如果…否则如果混淆c++
If...else if Confusion C++
我在使用if/else语句时感到非常困惑,我构造了一个程序来决定三个提供的整数中哪一个是最大值…我写了下面的代码:
int a,b,c,max;
cout<<"Please enter value 1: t";
cin>>a;
cout<<"Please enter value 2: t";
cin>>b;
cout<<"Please enter value 3: t";
cin>>c;
if(a>b)
{
if(a>c)
max=a;
}
else if(b>a)
{
if(b>c)
max=b;
}
else if(c>a) //here comes the problem
{
if(c>b)
max=c;
}
cout<<"The Max value among the given value is:t"<<max;
我为int a输入值12,为int b输入值13,为int c输入值14,(意思是如果我在第三个实例中提供最大值)它向我显示了一个垃圾值作为最大值(尽管有14),可能有什么问题请????我正在使用Dev c++ 5.5.1在32位windows 7.
更容易读的结构应该是这样的:
int maximum(int a, int b, int c) {
int max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
return max;
}
或更短的
if (a>= b&& a>= c)
cout << "The largest number is:" << a<< endl;
else if (b> =a&& b> =c)
cout << "The largest number is:" << b<< endl;
else if (c>= a&& c> =b)
cout << "The largest number is:" << c<< endl;
正确格式化代码很简单,包括:
- 正确对齐
{
和}
- 与缩进 一致
int a,b,c,max;
cout<<"Please enter value 1: t";
cin>>a;
cout<<"Please enter value 2: t";
cin>>b;
cout<<"Please enter value 3: t";
cin>>c;
if(a>b) {
if(a>c)
max=a;
} else if(b>a) {
if(b>c)
max=b;
} else if(c>a) {
if(c>b)
max=c;
}
cout<<"The Max value among the given value is:t"<<max;
相关文章:
- 如果没有malloc,链表实现将失败
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 如果编译的源代码是特定于它编译的硬件的,我们如何分发它
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- C++擦除(如果存在)
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 在'如果'陈述输出如何正确
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 如果基类包含双指针成员,则派生类的构造函数
- 如果没有数学库,我如何在C++中创建复利公式
- 如果我已经有一个头,那么模板(-t)文件属于哪里
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?