gpt4 book ai didi

c++ - 为什么编译器告诉我在 'if'和 'else if'语句中没有运算符与操作数类型匹配?

转载 作者:行者123 更新时间:2023-12-02 09:47:47 25 4
gpt4 key购买 nike

这段代码有什么问题?我一直在尝试,但是我不知道为什么我不能在=语句中使用==if

#include <vector>

#include <cstdlib>

#include <time.h>

using namespace std;

/* I am trying to make the program output a periodic t symbol

so then it asks the user what the element is */

void symbols(std::vector<std::string> alcalinos) {

alcalinos = { "H", "Li", "Na", "K", "Rb", "Cs", "Fr" };

std::string elemento;

cout << "Introduce el elemento correspondiente al símbolo(en minusculas) : \n";

srand(time(NULL));

int random = rand() % 7;

cout << alcalinos[random];

cin >> elemento;

if ((alcalinos = "H") && (elemento = "hidrogeno")) {

cout << "correcto\n";

}

else if ((alcalinos = "Li") && (elemento = "litio")) {

cout << "correcto\n";

}

else if ((alcalinos = "Na") && (elemento = "sodio")) {

cout << "correcto\n";

}

else if ((alcalinos = "K") && (elemento = "potasio")) {

cout << "correcto\n";

}

else if ((alcalinos = "Rb") && (elemento = "rubidio")) {

cout << "correcto\n";

}

else if ((alcalinos = "Cs") && (elemento = "cesio")) {

cout << "correcto\n";

}

else if ((alcalinos = "Fr") && (elemento = "francio")) {

cout << "correcto\n";

}

else {

cout << "incorrecto\n";

}





int main(); {

void symbols();



}

最佳答案

我必须心情愉快,我添加了评论以指出您犯的错误

void symbols() { // no parameter for function

// local declaration of vector instead of parameter
std::vector<std::string> alcalinos = { "H", "Li", "Na", "K", "Rb", "Cs", "Fr" };

std::string elemento;

cout << "Introduce el elemento correspondiente al símbolo(en minusculas) : \n";


int random = rand() % 7;

cout << alcalinos[random];

cin >> elemento;

// compare alcalinos[random] not alcalinos
// use == not =
if ((alcalinos[random] == "H") && (elemento == "hidrogeno")) {
cout << "correcto\n";
}
else if ((alcalinos[random] == "Li") && (elemento == "litio")) {
cout << "correcto\n";
}
else {
cout << "incorrecto\n";
}
} // missing }





int main() { // no ; after main()

srand(time(NULL)); // seed RNG once in main

symbols(); // no void before function call
}
当您犯了很多错误时,这意味着您试图一次编写太多代码。当您是初学者时,一次只能在一行中添加代码。并在添加的每一行之后测试代码。这样,您只想一次解决一个问题。您会发现这种方式要容易得多。

关于c++ - 为什么编译器告诉我在 'if'和 'else if'语句中没有运算符与操作数类型匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63907605/

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