2011-10-04 62 views
2

我會盡可能具體.. 我有這樣的代碼:簡化和重寫我的代碼

// bintodec.cpp : Defines the entry point for the console application. 

#include "stdafx.h" 
#include <iostream> 
#include <string> 

using namespace std; 

int main(){ 
    string inp; 
    int dec = 0; 
    char base; 
    cout << "Input a number: "; 
    cin >> inp; 
    cout << "Input the base your number is in: "; 
    cin >> base; 
    for (int i = inp.length()-1, j = 0; i >= 0; i--, ++j) 
     dec += (inp[i]-48) * pow((float)base-48, j); 
    cout << "Your number in base 10 is: " << dec <<endl; 
    system("pause"); 
    return 0; 
} 

我試圖重寫/簡化IT..to:

{ 
    int j=0,x; 
    double dec,y; 
    for(int i = inp.length()-1; i >= 0; i--) 
    { 
    x=(inp[i]-48); 
    y=pow((float)base-48, j); 
    dec=dec + x * y; 
    ++j; 
    } 
} 

我有:

int j=0,x; 
    double dec, y; 
     char base, inp; 

     cout << "Input a number: "; 
    cin >> inp; 
    cout << "Input the base your number is in: "; 
    cin >> base; 


     { 
      for (int i = inp.length()-1; i>=0; --i) 
      x=(inp[i]-48); 
      y=pow((float)base-48, j); 
      dec=dec + (x*y) 
       ++j; 
      { 
      return 0; 

出於某種原因,它不是working..visual工作室報道說:

  1. 「長度」的左側必須具有類/結構/聯合類型是‘字符’
  2. 下標要求數組或指針類型
  3. ‘++’需要-1-值
  4. 語法錯誤:缺少';'標識符'j'前

我想重寫和簡化它..幫助錯誤請..謝謝!

+1

這是功課? – SpeedBirdNine

+0

即時通訊猜測你問的問題是hw是識別錯誤..沒有它不是 –

+0

我問這是這個作業,所以它的作業是我可以添加一個作業標籤到您的問題 – SpeedBirdNine

回答

6

1:您不能做inp.length(),因爲您將inp聲明爲char。而一個字符不是一個字符串。

嘗試聲明inp作爲string

string inp; 

2: 「下標要求數組或指針型」

同上原因。 inp是一個char而不是數組或字符串。

3/4: 「 '+' 需要L值」

你失蹤分號:dec=dec + (x*y)

+0

我也使用字符串基地? TY! –

+0

不需要,你應該使用:'char base;'(這是正確的方式) – Mysticial

+0

你確定base是好的嗎?它不需要用'base - ='0'來糾正';'? –