学习if语句.这行吗

Learning if statements. Would this work?

本文关键字:语句 if 学习      更新时间:2023-10-16

这个代码能工作吗?它似乎没有任何错误,但我的编译器不会显示任何结果:

#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 i5int变量将此伪代码转换为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语句的原因。

  1. 您正在修改传入的最小值。不要这样做
  2. 在函数中创建一个int类型的局部变量,并使用它来跟踪最小的变量
  3. 去掉else,只做if。你需要检查所有传入的整数
  4. 只将最小的i保存到局部变量中。如果其他i变量中的一个较小,它将被覆盖。
    1. 返回局部变量,而不是0
  5. 创建一个int main函数,并使用main中的所有必要参数调用最小函数
  6. 将结果保存到main中的本地int中
  7. 打印出结果

此代码中没有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;
}