Jump to content

Exercitiu C++: Maximul Unor Numere Naturale


Vlăduț Rădulescu

Recommended Posts

Salutare, PC Troubleshooting. Sunt în Code::Blocks să fac o problemă pentru informatică.

 

Proiectul este acesta:

#include <iostream>

using namespace std;

int main()
{int n, max, x;
max=0;
do
{
    cout<<"n=";
    cin>>n;
    x=n;
    if (x>max)
        max=x;
}while (n=!0);
    cout<<max<<" ";
}

Credeți că este corect? Problema este ceva de genul:

 

Se citesc pe rând numere naturale până la întâlnirea valorii 0. Determinați maximul dintre aceste numere. Presupunem că în șir sunt cel puțin două elemente nenule.

 

Link to comment
Share on other sites

  • Moderators

Nu inteleg de ce folosesti x. while (n=!0) ar trebui sa fie while (n!=0) (echivalent cu while(n))

#include <iostream>

using namespace std;

int main()
{
    unsigned n, max = 0;
    do
    {
        cout << "n=";
        cin >> n;
        if (n > max)
            max = n;
    }while (n);

    cout << "Maximul este: " << max;

    return 0;
}
Link to comment
Share on other sites

inafara ca folosesti mai putine variabile, codu face acelasi lucru, nu? Sau nu observ eu ceva? :)) (inafara de faza ca faci verificarea la sfarsit, ceea ce poate fi o problema daca se citesc numere negative.. caz in care doar varianta lu courage ar merge bine)

love is a verb
Love is a doing word

Link to comment
Share on other sites

Pai, se putea mult mai simplu :) Foloseai un while cu conditia: cin >> n, iar codul ar fi aratat ceva de genul:

while(cin >> n) {
   maxim = max(n, maxim);
}

cout << maxim << 'n';

// 0, ultima valoarea citita mai exact, nu poate fi maxim, deci nu vor fi probleme la afisare 

Daca iti iese un program din prima, inseamna ca ceva e gresit...

Link to comment
Share on other sites

  • Moderators

 

Pai, se putea mult mai simplu :) Foloseai un while cu conditia: cin >> n, iar codul ar fi aratat ceva de genul:

while(cin >> n) {
   maxim = max(n, maxim);
}

cout << maxim << 'n';

// 0, ultima valoarea citita mai exact, nu poate fi maxim, deci nu vor fi probleme la afisare 

 

Citesti la infinit.

 

Schimba

while(cin >> n) {

cu

while(cin >> n and n) {
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.