c++ - 关于四舍五入和产生正确输入的代码帮助

标签 c++ c

<分区>

问题:

Your task is to:

Write a function that prints to the standard output (stdout) the number of users who didn't leave the site after 10 seconds (i.e: the number of users who didn't bounce).

Please round the result downwards to the nearest integer (e.g both 7.1 and 7.9 are rounded to 7).

Note that your function will receive the following arguments:

n which is an integer representing the number of visitors

b which is an integer representing the bounce rate (i.e: the percentage of users who left the site in the first 10 seconds)

我的代码编译得很好,我很确定我的逻辑是正确的,但我的输出是错误的,我不知道为什么。当 n = 1000b = 25 时,我的结果应该是 750。我不断获得 1000。我哪里错了?

我也不确定如何按照他们希望我的方式“舍入”。这也可能是我没有得到正确输出的原因吗?

我的代码:

void compute_active_users(int n, int b) {

    int BounceConvert = (b / 100); //converts the value of b to a decimal
    int BounceRate = (n * BounceConvert); // multiplys n times the b decimal
    int TotalVisitors = (n - BounceRate); // subtract BounceRate  

    printf("%d", TotalVisitors); // print out the final result

}

最佳答案

这对正整数使用 C 中整数除法的截断行为,这是您练习的目标:

void compute_active_users(int nbPeople, int bounceRate) {
    int totalVisitors = nbPeople * (100 - bounceRate) / 100;  
    printf("%d\n", totalVisitors);
}

您的解决方案不起作用,因为这一行:

int BounceConvert = (b / 100);

将产生 BounceConvert=0 (25/100 -> 0)

关于c++ - 关于四舍五入和产生正确输入的代码帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23744361/

相关文章:

c++ - 了解线程构造函数的基础知识

c++ - 如何将字符附加到 std::string?

c++ - 如何获取 IWebBrowser2 的实例

c++ - GCC如何处理变量重定义

c - 检测 char 数组中有多少行

c++ - 如何解释 sizeof(std::vector<int>) 的值?

c++ - 用两个 vector 编写结构模板

c# - 从 C# 调用不安全的 C++ 时出现 System.AccessViolationException

c - 使用标准 C 套接字下载互联网图像时遇到问题

c - 使用宏中的#define