【问题标题】:Product of char values in a cstring?cstring中char值的乘积?
【发布时间】:2016-01-22 21:20:52
【问题描述】:

免责声明:作为一个自称 C++ 菜鸟,我可能做了一个愚蠢的疏忽。请不要生气;)

无论如何,我正在尝试创建一个函数,将大写 cstring 的每个单独字符转换为 int (a=1,b=2,...),然后将这些值相乘。这是我的代码:

int product(char s[]) {
int curProd = 1;
for (size_t i = 0; i < strlen(s);++i) {
    if (s[i] = 'A') {
        curProd = curProd * 1;
    }
    if (s[i] = 'B') {
        curProd = curProd * 2;
    }
    if (s[i] = 'C') {
        curProd = curProd * 3;
    }

等等等等。我试图用

来测试这个
int main() {
char x[] = "HI";
printf("%d",product(x));
return(0);
}

运行时,输出为 0。谁能告诉我这段代码有什么问题?

【问题讨论】:

  • 为了速度for (size_t i = 0; i &lt; strlen(s);++i) {改成for (size_t i = 0; s[i];++i) {
  • 保存键盘if (s[i] = 'A') {... etc 一行就足够了,即curProd = curProd * (1 + s[i] - 'A')
  • 你确定你最后得到了return curProd

标签: c++ char c-strings


【解决方案1】:

你想要==,而不是=。你应该注意你的编译器警告。

【讨论】:

  • 并确保他们出现(例如-Wall/Wall
  • @EdHeal:不一定。也许最后一个字母乘以 0。取决于“等等等等”的作用。
【解决方案2】:

为什么不直接将 ASCII 字符转换为整数然后减去 64?这将消除对所有 if 语句的需要。

【讨论】:

  • 喜欢我的评论建议吗?!
  • 对不起,我错过了:(
猜你喜欢
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 2015-08-07
  • 2011-11-02
  • 2020-06-12
  • 2010-10-25
相关资源
最近更新 更多