学习if语句.这行吗
Learning if statements. Would this work?
这个代码能工作吗?它似乎没有任何错误,但我的编译器不会显示任何结果:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
/* declaration */
int smallest (int i1, int i2, int i3, int i4, int i5, int smallest){
if (i1 < smallest){
smallest = i1;
}
else if (i2 < smallest) {
smallest = i2;
}
else if (i3 < smallest) {
smallest = i3;
}
else if (i4 < smallest) {
smallest = i4;
}
else if (i5 < smallest){
smallest = i5;
}
else {
smallest = smallest;
}
return (0);
}
我正在为我的into to C++课程做硬件作业,这是问题之一。
假设我有五个名为i1, i2, i3, i4, and i5
的int变量将此伪代码转换为C或C++代码:
let smallest = smallest(i1, i2, i3, i4, i5)
在他的讲义上,他也展示了类似的例子
std::string smallest;
std::string largest;
if (s < t) {
smallest = s;
largest = t;
}
else if (s > t) {
smallest = t;
largest = s;
}
else {
smallest = t; //change the value that is stored in s
largest = s; //change the value that is stored in t
}
std::cout << smallest << std::endl;
std::cout << largest << std::endl;
这就是我使用if-else语句的原因。
- 您正在修改传入的最小值。不要这样做
- 在函数中创建一个int类型的局部变量,并使用它来跟踪最小的变量
- 去掉else,只做if。你需要检查所有传入的整数
- 只将最小的i保存到局部变量中。如果其他i变量中的一个较小,它将被覆盖。
- 返回局部变量,而不是0
- 创建一个int main函数,并使用main中的所有必要参数调用最小函数
- 将结果保存到main中的本地int中
- 打印出结果
此代码中没有main()
函数,因此不会发生任何事情,也无法调用该函数。
附带说明一下,一旦函数退出,就不会修改变量smallest
。请尝试返回smallest
。
假设您通过4,3,2,1,最小值为5。然后您的函数(应该返回值smallest
而不是0
(将报告4是最小的。您需要删除else
分支,并验证您传递的每个值。
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
int checkSmallest(int i1, int i2, int i3, int i4, int i5);
int _tmain(int argc, _TCHAR* argv[])
{
int smallestAtm = checkSmallest(-8, 4, 3, 7, 8);
cout << smallestAtm;
std::cin.get();
return 0;
}
int checkSmallest(int i1, int i2, int i3, int i4, int i5)
{
int curSmallest = 0;
if (i1 < curSmallest)
curSmallest = i1;
if (i2 < curSmallest)
curSmallest = i2;
if (i3 < curSmallest)
curSmallest = i3;
if (i4 < curSmallest)
curSmallest = i4;
if (i5 < curSmallest)
curSmallest = i5;
return curSmallest;
}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 我似乎对if/else的基本语句有问题:/
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果中的多个语句是否与多个 if 相同?
- C++ If/Else 语句被跳过
- 使用语句if时逻辑的问题
- 如何添加语句if-else
- 如何将语句if(isalpha(c))从c++转换为MIPS ?
- 在if语句if C++中创建对象时出现作用域问题
- if语句-if/else和参数放置C++