【问题标题】:How to input text in the struct variable and then compare it?如何在结构变量中输入文本,然后进行比较?
【发布时间】:2022-12-06 00:48:13
【问题描述】:

根据任务,我需要计算外国优秀学生的百分比(因此原籍国不是“乌克兰”并且平均分数大于 3)。但它不会工作,我不知道我是否正确地在结构变量中输入文本并比较它。请解释一下。

编码:

#include <iostream>
#include <ctime>
#include <Windows.h>
#include <cmath>
#include <iomanip>
using namespace std;

struct Student {
    char country[15];
    int course;
    float meanMark;
};
int main() {
    Student s[4];
    //strcpy_s(s.country, "hjkhj");
    //s.country = "ffff";
    for (int i = 0; i < 4; i++) {
        cout << "Student" << i + 1 << ": " << "\n";
        std::cin >> s[i].country;
        cin >> s[i].course;
        cin >> s[i].meanMark;
    }
    char u[8] = "Ukraine";
    int k = 0;
    for (int i = 0; i < 4; i++) {
        if (s[i].country != u && s[i].meanMark > 3) {
            k++;
        }
    }
    float percent = k / 4 * 100;
    cout << "percent = " << percent << "%" << endl;
}

这是输入:
首先是原产国,而不是当然,而不是平均标记

https://i.stack.imgur.com/kzdKz.png
这是输出:
结果应该是25%
https://i.stack.imgur.com/7lhNd.png

【问题讨论】:

  • 如果您要使用 C 字符串,请使用 strcmp。但最好使用std::string
  • s[i].country != u 不会比较 C 字符串。你的编译器没有警告你吗?

标签: c++


【解决方案1】:

我认为你需要的是修改计算百分比的行

float percent = k / 4.0 * 100.0;

【讨论】:

    【解决方案2】:

    好的,所以我将 char 更改为 string,但它再次不起作用,但后来我用 / 4* 100 更改了位置,所以等式看起来像 float percent = k * 100 / 4;.... 它起作用了......

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      相关资源
      最近更新 更多