小编Sle*_*der的帖子

C ++中的三元条件运算符问题

我的目标:输入两个整数,并对所有从小数到大数的整数求和。

#include <iostream>
int main() {
    int v1, v2;
    std::cout << "Enter two integers: " << std::endl;
    std::cin >> v1 >> v2;

    int big, small;
    big = v1 > v2 ? v1, small = v2 : v2, small = v1;

    int sum = 0;
    for (int i = small; i <= big; i++)
        sum += i;
    std::cout << "The sum is " << sum << std::endl;

    getchar();
    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我要测试三元条件运算符,而不是使用if语句。

当v1小于或等于v2时,例如

Enter two integers: 
1
5
The …
Run Code Online (Sandbox Code Playgroud)

c++ integer ternary-operator

1
推荐指数
1
解决办法
82
查看次数

可以使用可更改的 const 变量在 C 和 C++ 中声明和定义数组吗?

看下面的代码:

#include <iostream>
int main(void) {
    int  number1 = 4;
    double salary[number1];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

虽然可以成功编译,但应该认为是错误的,因为 number1 是非 const 变量。

#include <iostream>

int main(void) {
    int  number1 = 4;

    const unsigned number2 = number1;
    double salary[number2];

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在 number2 是一个常量变量。

也编译成功。

我觉得这是错误的,或者至少不是好的做法。

但我无法解释为什么。

有人可以解释为什么它是错误的吗?

c c++ arrays constants

1
推荐指数
1
解决办法
115
查看次数

当vector过大时,如何解决C++内存不足的问题?

测试两个向量是否相同

见下面的代码

#include <iostream>
#include <vector>
#include <string>
int main(void) {
    std::vector<std::string> vstr1(131, "asdf");
    std::vector<std::string> vstr2(33131, "asdf");

    std::cout << (vstr1 == vstr2) << std::endl;;
    std::cout << "******************************" << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它工作正常。

现在我将vstr2的大小更改为非常,例如33333333333131

#include <iostream>
#include <vector>
#include <string>
int main(void) {
    std::vector<std::string> vstr1(131, "asdf");
    std::vector<std::string> vstr2(33333333333131, "asdf");

    std::cout << (vstr1 == vstr2) << std::endl;;
    std::cout << "******************************" << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

不工作,错误信息是

terminate called after throwing an instance of 'std::bad_alloc' 
what()  std::bad_alloc …
Run Code Online (Sandbox Code Playgroud)

c++ memory allocation vector large-data

1
推荐指数
1
解决办法
509
查看次数

为什么sqrt()指定的浮点数没有精度损失?

我想了解C如何处理浮点数的精度损失.

这是我的简单代码:

#include <stdio.h>
#include <math.h>

int main ()
{
    double a;
    int i;
    i = 7;
    a = sqrt(i);

    printf("i = %d, a = %lf\n", i, a); 
    printf("a * a = %lf\n", a*a);

    a = 2.645751;
    printf("a * a = %lf\n", a*a);

    return(0);
}
Run Code Online (Sandbox Code Playgroud)

以下是cc之后的结果

i = 7,a = 2.645751

a*a = 7.000000

a*a = 6.999998

如果直接分配一个2.645751的浮点数,a*a的结果对我来说是可以理解的.

但是如果a被分配了sqrt(7),为什么a*a的输出没有精度损失?

这对我来说很难理解.

c precision

0
推荐指数
1
解决办法
108
查看次数