gpt4 book ai didi

C++临时变量解释

转载 作者:行者123 更新时间:2023-11-28 03:34:26 25 4
gpt4 key购买 nike

我已经搜索过临时变量是什么意思,但我无法搜索也无法理解。我已经完成了没有临时变量的 if-else 结构,现在我正在尝试执行 if-else 结构和临时变量。我找不到区别。

问题是

  1. 编写一个程序,读取三个整数(a、b 和 c)并使用 if else 结构和一个临时变量打印出最大值。
  2. 没有临时变量的 if else 结构。

我已经完成了第一题。

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int a,b,c;

cout<<"a : ";
cin>>a;
cout<<"b : ";
cin>>b;
cout<<"c : ";
cin>>c;

if(a>b && a>c)
{
cout<<"largest : "<<a;
}else{
if(b>a && b>c)
{
cout<<"largest : "<<b;
}else{
if(c>a && c>b)
{
cout<<"largest : "<<a;
}else{
cout<<"error!";
}
}
}


getch();
return 0;
}

但是对于第二个问题是这样的吗?

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int a,b,c;
int max;

cout<<"a : ";
cin>>a;
cout<<"b : ";
cin>>b;
cout<<"c : ";
cin>>c;


if(a>b && a>c)
{
max=a;
cout<<"largest : "<<max;
}else{
if(b>a && b>c)
{
max=b;
cout<<"largest : "<<max;
}else{
if(c>a && c>b)
{
max=c;
cout<<"largest : "<<max;
}else{
cout<<"error!";
}
}
}


getch();
return 0;
}

我只是想确认一下,因为我不完全理解临时变量是什么意思。谢谢。

最佳答案

“临时”的确切含义可能会有所不同,但在这种情况下,它仅表示用于保存输入的变量以外的变量。我认为更好的术语可能是“中间”。

当您只是试图找到三个值中的最大值时,有点难以看出使用中间变量的优势,但想象一下如果您试图找到 100 个值中的最大值。如果没有中间变量,你会怎么做?

关于C++临时变量解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11488827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com