c++ - 在 C++ 中将小数与变量相乘时出错

标签 c++ decimal

我是一名学生,最近开始学习 C++。我正在用 C++ 为我的后辈制作 GPA 计算器,但我遇到了一个错误。当我将一个小数与一个变量相乘时,我每次都会得到相同的答案。这只发生在小数点上。精确整数工作正常。 如果我将变量“cal”的值放在整数范围内,我会得到正确的答案。就像如果我放置 85,我会得到 12 作为输出,但是当我输入低于 85 的值时,我每次都会得到 3.1。

你能指出我的错误吗?

这是我的起始源代码:

#include <iostream>
#include <string>
using namespace std;
    int main()
        {double cal,calh,c1;
        cout<< "How many marks you obtained in calculus? \n";
        cin >>cal;
        cout<<"Enter the credit hours of Calculus? \n";
        cin>>calh;
        if (cal>85 || cal==85){c1=4*calh;}
        else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
        else if (cal>75 || cal==75 || cal<80){c1=3.3*calh;}
        else if (cal>70 || cal==70 || cal<75){c1=3*calh;}
        else if (cal>65 || cal==65 || cal<70){c1=2.7*calh;}
        else if (cal>61 || cal==61 || cal<65){c1=2.3*calh;}
        else if (cal>58 || cal==58 || cal<61){c1=2*calh;}
        else if (cal>55 || cal==55 || cal<58){c1=1.7*calh;}
        else if (cal>50 || cal==50 || cal<55){c1=1*calh;}
        else if (cal<50 || cal==49){cout<<"Sorry but you are failed in calculus.";}
        cout<<"your total gpa in calculus is "<< c1<<endl;
        system("pause");
        return 0;
    }

最佳答案

想想你写了什么

else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}

这将匹配所有内容(任何数字大于 80 小于 85)

你想要这样的东西

#include <iostream>
#include <string>
using namespace std;
int main()
{
  double cal, calh, c1;
  cout << "How many marks you obtained in calculus? \n";
  cin >> cal;
  cout << "Enter the credit hours of Calculus? \n";
  cin >> calh;
  if (cal >= 85) { c1 = 4 * calh; }
  else if (cal >= 80) { c1 = 3.7*calh; }
  else if (cal >= 75) { c1 = 3.3*calh; }
  else if (cal >= 70) { c1 = 3 * calh; }
  else if (cal >= 65) { c1 = 2.7*calh; }
  else if (cal >= 61) { c1 = 2.3*calh; }
  else if (cal >= 58) { c1 = 2 * calh; }
  else if (cal >= 55) { c1 = 1.7*calh; }
  else if (cal >= 50) { c1 = 1 * calh; }
  else { cout << "Sorry but you are failed in calculus."; c1 = 0; }
  cout << "your total gpa in calculus is " << c1 << endl;
  system("pause");
  return 0;
}

关于c++ - 在 C++ 中将小数与变量相乘时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42270049/

相关文章:

用于将对象流的转换链接在一起的 C++ 设计模式

c++ - 如何让CMake在任何地方自动添加MagickWand库链接

javascript - 在 jQuery 中替换小数

java - 尝试在java中四舍五入到小数点后两位

c# - 哪个是实例化小数的更好方法?

c++ - 检查类是否有指针数据成员

main 之后的 c++ 类声明?

c++ - 使用 Boost 库生成非常大的随机数

java - 如何获取十进制符号

在 C 中使用位掩码和移位将十进制转换为十六进制