gpt4 book ai didi

c++ - 如何在 lambda 表达式中传递变量?

转载 作者:行者123 更新时间:2023-11-30 02:13:30 24 4
gpt4 key购买 nike

我现在正在练习 lambda 表达式,我做的这个程序是获取一个主题的加权平均值,第一个 lambda 表达式 'get_avg' 是获取数据,而过程是 'sum_avg',当它运行时,sum_avg 正在输出 '-nan(ind)' 这不是我想要的答案。

#include<iostream>
#include<thread>
using namespace std;
int main() {
float m = 0, w = 0;
auto get_avg = [](float m, float w) {

cout << "ENTER THE GRADE: ";
cin >> m;
cout << "ENTER THE UNITS: ";
cin >> w;
return m, w;
};
get_avg(m, w);
auto sum_avg = [](float m,float w){
cout << "THE WEIGHTED AVERAGE IS :" <<m*w/w << endl;
};
sum_avg(m,w);
system("PAUSE");
return 0;
}

最佳答案

为了能够更改 main 函数的 mw 的值,您需要将它们传递到 get_avg lambda 引用:

// you didn't need <thread> header, don't include it
#include<iostream>

// Never ever take the whole std namespace into your program!
// Take only the names you need,
// or just use the fully qualified names, e.g. std::cout everywhere.
using std::cin;
using std::cout;
using std::endl;

int main() {
float m = 0, w = 0;
auto get_avg = [](float &m, float &w) {
cout << "ENTER THE GRADE: ";
cin >> m;
cout << "ENTER THE UNITS: ";
cin >> w;
};
get_avg(m, w);
auto sum_avg = [](float m,float w){
cout << "THE WEIGHTED AVERAGE IS :" <<m*w/w << endl;
};
sum_avg(m,w);
system("PAUSE"); // I'm not sure why you use this here.
return 0;
}

您也可以按值获取变量,并返回 std::pair来自第一个 lambda。然后你可以使用 std::tie将其返回值赋给m,和w:

#include <iostream>
#include <tuple>
#include <utility>

int main() {
float m = 0, w = 0;
auto get_avg = [](float m, float w) {
std::cout << "ENTER THE GRADE: ";
std::cin >> m;
std::cout << "ENTER THE UNITS: ";
std::cin >> w;
return std::make_pair(m, w);
};
std::tie(m, w) = get_avg(m, w);
auto sum_avg = [](float m, float w){
std::cout << "THE WEIGHTED AVERAGE IS :" << m*w/w << std::endl;
};
sum_avg(m, w);
return 0;
}

顺便说一下,这个 m*w/w 并没有真正做很多事情,我让你找出原因。

关于c++ - 如何在 lambda 表达式中传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59159744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com